blob: 8352c7f58482a27cb2cab38bcc0c768cc9f3ae8b [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 }
Eric Laurente552edb2014-03-10 17:42:56 -0700264
Eric Laurent87ffa392015-05-22 10:32:38 -0700265 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
267 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700268 }
jiabinbce0c1d2020-10-05 11:20:18 -0700269 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100270 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700271 const DeviceVector activeMediaDevices =
272 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700274 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530275 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
276 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100277 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700278 // do not force device change on duplicated output because if device is 0, it will
279 // also force a device 0 for the two outputs it is duplicated to which may override
280 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100281 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100282 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700284 // always force when disconnecting (a non-duplicated device)
285 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100286 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700287 }
jiabinbce0c1d2020-10-05 11:20:18 -0700288 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
289 desc->devices() != activeMediaDevices &&
290 desc->supportsDevicesForPlayback(activeMediaDevices)) {
291 // Reopen the output to query the dynamic profiles when there is not active
292 // clients or all active clients will be rerouted. Otherwise, set the flag
293 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
294 // can be reopened to query dynamic profiles when all clients are inactive.
295 if (areAllActiveTracksRerouted(desc)) {
296 outputsToReopen.push_back(mOutputs.keyAt(i));
297 } else {
298 desc->mPendingReopenToQueryProfiles = true;
299 }
300 }
301 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
302 // Clear the flag that previously set for re-querying profiles.
303 desc->mPendingReopenToQueryProfiles = false;
304 }
305 }
306 for (const auto& output : outputsToReopen) {
307 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
308 closeOutput(output);
309 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
311
Eric Laurentd60560a2015-04-10 11:31:20 -0700312 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100313 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700314 }
315
Eric Laurent72aa32f2014-05-30 18:51:48 -0700316 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700317 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700318 } // end if is output device
319
Eric Laurente552edb2014-03-10 17:42:56 -0700320 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700321 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100322 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700323 switch (state)
324 {
325 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700326 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700327 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100328 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700329 return INVALID_OPERATION;
330 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700331
332 if (mAvailableInputDevices.add(device) < 0) {
333 return NO_MEMORY;
334 }
335
François Gaffie44481e72016-04-20 07:49:57 +0200336 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
337 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100338 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200339
Eric Laurent0dd51852019-04-19 18:18:58 -0700340 if (checkInputsForDevice(device, state) != NO_ERROR) {
341 mAvailableInputDevices.remove(device);
342
François Gaffie11d30102018-11-02 16:09:09 +0100343 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100344
345 mHwModules.cleanUpForDevice(device);
346
Eric Laurentd4692962014-05-05 18:13:44 -0700347 return INVALID_OPERATION;
348 }
349
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700353 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100355 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700356 return INVALID_OPERATION;
357 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700358
François Gaffie11d30102018-11-02 16:09:09 +0100359 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700360
361 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100362 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700363
François Gaffie11d30102018-11-02 16:09:09 +0100364 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700365
366 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100367
368 // remove device from mReportedFormatsMap cache
369 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700371
372 default:
François Gaffie11d30102018-11-02 16:09:09 +0100373 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700374 return BAD_VALUE;
375 }
376
Eric Laurent736a1022019-03-27 18:28:46 -0700377 // Propagate device availability to Engine
378 setEngineDeviceConnectionState(device, state);
379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700381 // As the input device list can impact the output device selection, update
382 // getDeviceForStrategy() cache
383 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700384
Eric Laurent87ffa392015-05-22 10:32:38 -0700385 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100386 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
387 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200389 // Reconnect Audio Source
390 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
391 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
392 checkAudioSourceForAttributes(attributes);
393 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700394 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700396 }
397
Eric Laurentb52c1522014-05-20 11:27:36 -0700398 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700400 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700401
François Gaffie11d30102018-11-02 16:09:09 +0100402 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700403 return BAD_VALUE;
404}
405
Eric Laurent736a1022019-03-27 18:28:46 -0700406void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
407 audio_policy_dev_state_t state) {
408
409 // the Engine does not have to know about remote submix devices used by dynamic audio policies
410 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
411 return;
412 }
413 mEngine->setDeviceConnectionState(device, state);
414}
415
416
Eric Laurente0720872014-03-11 09:30:41 -0700417audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100418 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700419{
Eric Laurent634b7142016-04-20 13:48:02 -0700420 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800421 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
422 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700423 (strlen(device_address) != 0)/*matchAddress*/);
424
425 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100426 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700427 device, device_address);
428 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
429 }
François Gaffie53615e22015-03-19 09:24:12 +0100430
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 DeviceVector *deviceVector;
432
Eric Laurente552edb2014-03-10 17:42:56 -0700433 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 deviceVector = &mAvailableInputDevices;
437 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100438 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700439 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 }
Eric Laurent634b7142016-04-20 13:48:02 -0700441
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800442 return (deviceVector->getDevice(
443 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800445}
446
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800447status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
448 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800449 const char *device_name,
450 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800451{
452 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700453 String8 reply;
454 AudioParameter param;
455 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800456
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800457 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
458 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800460 // connect/disconnect only 1 device at a time
461 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
462
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800463 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700464 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800466 // Nothing to do: device is not connected
467 return NO_ERROR;
468 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800469 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800470
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700471 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800472 // configure codecs.
473 // Handle two specific cases by sending a set parameter to
474 // configure A2DP codecs. No need to toggle device state.
475 // Case 1: A2DP active device switches from primary to primary
476 // module
477 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200478 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700479 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800480 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
481 if (availablePrimaryOutputDevices().contains(devDesc) &&
482 (module != 0 && module->getHandle() == primaryHandle)) {
483 reply = mpClientInterface->getParameters(
484 AUDIO_IO_HANDLE_NONE,
485 String8(AudioParameter::keyReconfigA2dpSupported));
486 AudioParameter repliedParameters(reply);
487 repliedParameters.getInt(
488 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
489 if (isReconfigA2dpSupported) {
490 const String8 key(AudioParameter::keyReconfigA2dp);
491 param.add(key, String8("true"));
492 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
493 devDesc->setEncodedFormat(encodedFormat);
494 return NO_ERROR;
495 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700496 }
497 }
cnx421bd2dcc42020-07-11 14:58:44 +0800498 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
499 for (size_t i = 0; i < mOutputs.size(); i++) {
500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
501 // mute media strategies and delay device switch by the largest
502 // This avoid sending the music tail into the earpiece or headset.
503 setStrategyMute(musicStrategy, true, desc);
504 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
505 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
506 nullptr, true /*fromCache*/).types());
507 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Toggle the device state: UNAVAILABLE -> AVAILABLE
509 // This will force reading again the device configuration
510 status = setDeviceConnectionState(device,
511 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 device_address, device_name,
513 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800514 if (status != NO_ERROR) {
515 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
516 status);
517 return status;
518 }
519
520 status = setDeviceConnectionState(device,
521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 if (status != NO_ERROR) {
524 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
525 status);
526 return status;
527 }
528
529 return NO_ERROR;
530}
531
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800532status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
533 std::vector<audio_format_t> *formats)
534{
535 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800536 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800537 std::unordered_set<audio_format_t> formatSet;
538 sp<HwModule> primaryModule =
539 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700540 if (primaryModule == nullptr) {
541 ALOGE("%s() unable to get primary module", __func__);
542 return NO_INIT;
543 }
jiabin9a3361e2019-10-01 09:38:30 -0700544 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
545 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800546 for (const auto& device : declaredDevices) {
547 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800548 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800549 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800550 return status;
551}
552
François Gaffie11d30102018-11-02 16:09:09 +0100553uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700554{
555 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100556 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700557 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700558
jiabin9a3361e2019-10-01 09:38:30 -0700559 if(!hasPrimaryOutput() ||
560 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700561 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700562 }
François Gaffie11d30102018-11-02 16:09:09 +0100563 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
564
Francois Gaffie716e1432019-01-14 16:58:59 +0100565 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100566 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100567 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100568
569 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100570 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700571
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200572 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700573 // release TX patch if any
574 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100575 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700576 mCallTxPatch.clear();
577 }
578
François Gaffie9eb18552018-11-05 10:33:26 +0100579 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700580 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100581 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700582 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100583 // retrieve Rx Source and Tx Sink device descriptors
584 sp<DeviceDescriptor> rxSourceDevice =
585 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
586 String8(),
587 AUDIO_FORMAT_DEFAULT);
588 sp<DeviceDescriptor> txSinkDevice =
589 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
590 String8(),
591 AUDIO_FORMAT_DEFAULT);
592
593 // RX and TX Telephony device are declared by Primary Audio HAL
594 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
595 (telephonyRxModule->getHalVersionMajor() >= 3)) {
596 if (rxSourceDevice == 0 || txSinkDevice == 0) {
597 // RX / TX Telephony device(s) is(are) not currently available
598 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
599 return muteWaitMs;
600 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100601 // createAudioPatchInternal now supports both HW / SW bridging
602 createRxPatch = true;
603 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100604 } else {
605 // If the RX device is on the primary HW module, then use legacy routing method for
606 // voice calls via setOutputDevice() on primary output.
607 // Otherwise, create two audio patches for TX and RX path.
608 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
609 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610 // If the TX device is also on the primary HW module, setOutputDevice() will take care
611 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100612 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
613 (txSinkDevice != 0);
614 }
615 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
616 // Otherwise, create two audio patches for TX and RX path.
617 if (!createRxPatch) {
618 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700619 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200620 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800621 // If the TX device is on the primary HW module but RX device is
622 // on other HW module, SinkMetaData of telephony input should handle it
623 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700625 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100626 // terminate active capture if on the same HW module as the call TX source device
627 // FIXME: would be better to refine to only inputs whose profile connects to the
628 // call TX device but this information is not in the audio patch and logic here must be
629 // symmetric to the one in startInput()
630 for (const auto& activeDesc : mInputs.getActiveInputs()) {
631 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
632 closeActiveClients(activeDesc);
633 }
634 }
François Gaffie9eb18552018-11-05 10:33:26 +0100635 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800636 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700637
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800638 return muteWaitMs;
639}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700640
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800641sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100642 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700643 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700644
François Gaffie11d30102018-11-02 16:09:09 +0100645 if (device == nullptr) {
646 return nullptr;
647 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100648
649 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800650 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100651 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800652 addSource(mAvailableInputDevices.getDevice(
653 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800654 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100655 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800656 addSink(mAvailableOutputDevices.getDevice(
657 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800658 }
659
François Gaffieafd4cea2019-11-18 15:50:22 +0100660 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
661 status_t status =
662 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
663 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
664 if (status != NO_ERROR || index < 0) {
665 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
666 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800667 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100668 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800669}
670
Mikhail Naganov100f0122018-11-29 11:22:16 -0800671bool AudioPolicyManager::isDeviceOfModule(
672 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
673 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
674 if (module != 0) {
675 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
676 .indexOf(devDesc) != NAME_NOT_FOUND
677 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
678 .indexOf(devDesc) != NAME_NOT_FOUND;
679 }
680 return false;
681}
682
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200683void AudioPolicyManager::connectTelephonyRxAudioSource()
684{
685 disconnectTelephonyRxAudioSource();
686 const struct audio_port_config source = {
687 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
688 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
689 };
690 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
691 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
692 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
693}
694
695void AudioPolicyManager::disconnectTelephonyRxAudioSource()
696{
697 stopAudioSource(mCallRxSourceClientPort);
698 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
699}
700
Eric Laurente0720872014-03-11 09:30:41 -0700701void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700702{
703 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100704 // store previous phone state for management of sonification strategy below
705 int oldState = mEngine->getPhoneState();
706
707 if (mEngine->setPhoneState(state) != NO_ERROR) {
708 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700709 return;
710 }
François Gaffie2110e042015-03-24 08:41:51 +0100711 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700712 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700714 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800715 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 }
717
François Gaffie2110e042015-03-24 08:41:51 +0100718 /**
719 * Switching to or from incall state or switching between telephony and VoIP lead to force
720 * routing command.
721 */
Eric Laurent74b71512019-11-06 17:21:57 -0800722 bool force = ((isStateInCall(oldState) != isStateInCall(state))
723 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700724
725 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700726 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700727
Eric Laurente552edb2014-03-10 17:42:56 -0700728 int delayMs = 0;
729 if (isStateInCall(state)) {
730 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100731 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
732 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700733 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700735 // mute media and sonification strategies and delay device switch by the largest
736 // latency of any output where either strategy is active.
737 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100738 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
739 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
740 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700741 (delayMs < (int)desc->latency()*2)) {
742 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700743 }
François Gaffiec005e562018-11-06 15:04:49 +0100744 setStrategyMute(musicStrategy, true, desc);
745 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
746 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
747 nullptr, true /*fromCache*/).types());
748 setStrategyMute(sonificationStrategy, true, desc);
749 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
750 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
751 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700752 }
753 }
754
Eric Laurent87ffa392015-05-22 10:32:38 -0700755 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100756 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700757 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100758 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700759 // force routing command to audio hardware when ending call
760 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100761 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
762 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700763 }
Eric Laurente552edb2014-03-10 17:42:56 -0700764
Eric Laurent87ffa392015-05-22 10:32:38 -0700765 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100766 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700767 } else if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768 disconnectTelephonyRxAudioSource();
Eric Laurent87ffa392015-05-22 10:32:38 -0700769 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100770 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700771 mCallTxPatch.clear();
772 }
François Gaffie11d30102018-11-02 16:09:09 +0100773 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700774 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100775 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700776 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700778
779 // reevaluate routing on all outputs in case tracks have been started during the call
780 for (size_t i = 0; i < mOutputs.size(); i++) {
781 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100782 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700783 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100784 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700785 }
786 }
787
Eric Laurente552edb2014-03-10 17:42:56 -0700788 if (isStateInCall(state)) {
789 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700790 // force reevaluating accessibility routing when call starts
791 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700792 }
793
794 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100795 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
796 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700797}
798
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700799audio_mode_t AudioPolicyManager::getPhoneState() {
800 return mEngine->getPhoneState();
801}
802
Eric Laurente0720872014-03-11 09:30:41 -0700803void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100804 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700805{
François Gaffie2110e042015-03-24 08:41:51 +0100806 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700807 if (config == mEngine->getForceUse(usage)) {
808 return;
809 }
Eric Laurente552edb2014-03-10 17:42:56 -0700810
François Gaffie2110e042015-03-24 08:41:51 +0100811 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
812 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
813 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700814 }
François Gaffie2110e042015-03-24 08:41:51 +0100815 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
816 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
817 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700818
819 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700820 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800821
Eric Laurent22fcda22019-05-17 16:28:47 -0700822 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
823 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
824 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
825 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
826 }
827
Eric Laurentdc462862016-07-19 12:29:53 -0700828 //FIXME: workaround for truncated touch sounds
829 // to be removed when the problem is handled by system UI
830 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700831 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
832 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
833 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700834
835 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100836 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700837}
838
Eric Laurente0720872014-03-11 09:30:41 -0700839void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700840{
841 ALOGV("setSystemProperty() property %s, value %s", property, value);
842}
843
Michael Chana94fbb22018-04-24 14:31:19 +1000844// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
845// search to profiles for direct outputs.
846sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100847 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000848 uint32_t samplingRate,
849 audio_format_t format,
850 audio_channel_mask_t channelMask,
851 audio_output_flags_t flags,
852 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700853{
Michael Chana94fbb22018-04-24 14:31:19 +1000854 if (directOnly) {
855 // only retain flags that will drive the direct output profile selection
856 // if explicitly requested
857 static const uint32_t kRelevantFlags =
858 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700859 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000860 flags =
861 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
862 }
Eric Laurent861a6282015-05-18 15:40:16 -0700863
864 sp<IOProfile> profile;
865
Mikhail Naganovd4120142017-12-06 15:49:22 -0800866 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800867 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100868 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700869 samplingRate, NULL /*updatedSamplingRate*/,
870 format, NULL /*updatedFormat*/,
871 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700872 flags)) {
873 continue;
874 }
875 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100876 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700877 continue;
878 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800879 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700880 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800881 continue;
882 }
Michael Chana94fbb22018-04-24 14:31:19 +1000883 if (!directOnly) return curProfile;
884 // when searching for direct outputs, if several profiles are compatible, give priority
885 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100886 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700887 continue;
888 }
889 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100890 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700891 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700892 }
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
894 }
Eric Laurent861a6282015-05-18 15:40:16 -0700895 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700896}
897
Eric Laurentf4e63452017-11-06 19:31:46 +0000898audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffiec005e562018-11-06 15:04:49 +0100900 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800901
902 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
903 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
904 // format, flags, etc. This may result in some discrepancy for functions that utilize
905 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
906 // and AudioSystem::getOutputSamplingRate().
907
François Gaffie11d30102018-11-02 16:09:09 +0100908 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700909 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700910
François Gaffie11d30102018-11-02 16:09:09 +0100911 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
912 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000913 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914}
915
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700916status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
917 const audio_attributes_t *srcAttr,
918 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700919{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700920 if (srcAttr != NULL) {
921 if (!isValidAttributes(srcAttr)) {
922 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
923 __func__,
924 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
925 srcAttr->tags);
926 return BAD_VALUE;
927 }
928 *dstAttr = *srcAttr;
929 } else {
930 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
931 ALOGE("%s: invalid stream type", __func__);
932 return BAD_VALUE;
933 }
François Gaffiec005e562018-11-06 15:04:49 +0100934 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700935 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700936
937 // Only honor audibility enforced when required. The client will be
938 // forced to reconnect if the forced usage changes.
939 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700940 dstAttr->flags = static_cast<audio_flags_mask_t>(
941 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700942 }
943
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700944 return NO_ERROR;
945}
946
Kevin Rocard153f92d2018-12-18 18:33:28 -0800947status_t AudioPolicyManager::getOutputForAttrInt(
948 audio_attributes_t *resultAttr,
949 audio_io_handle_t *output,
950 audio_session_t session,
951 const audio_attributes_t *attr,
952 audio_stream_type_t *stream,
953 uid_t uid,
954 const audio_config_t *config,
955 audio_output_flags_t *flags,
956 audio_port_handle_t *selectedDeviceId,
957 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700958 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800959 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700960{
François Gaffiec005e562018-11-06 15:04:49 +0100961 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100962 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100963 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100964 const sp<DeviceDescriptor> requestedDevice =
965 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
966
Eric Laurent8a1095a2019-11-08 14:44:16 -0800967 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700968 status_t status = getAudioAttributes(resultAttr, attr, *stream);
969 if (status != NO_ERROR) {
970 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700971 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700972 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700973 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700974 }
François Gaffiec005e562018-11-06 15:04:49 +0100975 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700976
François Gaffiec005e562018-11-06 15:04:49 +0100977 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
978 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700979
Kevin Rocard153f92d2018-12-18 18:33:28 -0800980 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
981 // otherwise, fallback to the dynamic policies, if none match, query the engine.
982 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700983 sp<AudioPolicyMix> primaryMix;
984 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700985 if (status != OK) {
986 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800987 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700988
Kevin Rocard153f92d2018-12-18 18:33:28 -0800989 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700990 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800991
992 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700993 if ((usePrimaryOutputFromPolicyMixes
994 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800995 && !audio_is_linear_pcm(config->format)) {
996 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800997 return BAD_VALUE;
998 }
999 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001000 sp<DeviceDescriptor> deviceDesc =
1001 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1002 primaryMix->mDeviceAddress,
1003 AUDIO_FORMAT_DEFAULT);
1004 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001005 if (deviceDesc != nullptr
1006 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001007 audio_io_handle_t newOutput;
1008 status = openDirectOutput(
1009 *stream, session, config,
1010 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1011 DeviceVector(deviceDesc), &newOutput);
1012 if (status != NO_ERROR) {
1013 policyDesc = nullptr;
1014 } else {
1015 policyDesc = mOutputs.valueFor(newOutput);
1016 primaryMix->setOutput(policyDesc);
1017 }
1018 }
1019 if (policyDesc != nullptr) {
1020 policyDesc->mPolicyMix = primaryMix;
1021 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001022 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001023
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001024 ALOGV("getOutputForAttr() returns output %d", *output);
1025 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1026 *outputType = API_OUT_MIX_PLAYBACK;
1027 } else {
1028 *outputType = API_OUTPUT_LEGACY;
1029 }
1030 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001031 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001032 }
François Gaffiec005e562018-11-06 15:04:49 +01001033 // Virtual sources must always be dynamicaly or explicitly routed
1034 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1035 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1036 return BAD_VALUE;
1037 }
1038 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1039 // in order to let the choice of the order to future vendor engine
1040 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001041
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001042 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001043 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001044 }
1045
Nadav Barb2f18162018-07-18 13:01:53 +03001046 // Set incall music only if device was explicitly set, and fallback to the device which is
1047 // chosen by the engine if not.
1048 // FIXME: provide a more generic approach which is not device specific and move this back
1049 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001050 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001051 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001052 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001053 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001054 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001055 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001056 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001057 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001058 }
1059 }
1060
François Gaffiec005e562018-11-06 15:04:49 +01001061 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1062 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1063 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001064
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001065 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001066 if (!msdDevices.isEmpty()) {
1067 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001068 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001069 ALOGV("%s() Using MSD devices %s instead of devices %s",
1070 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001071 } else {
1072 *output = AUDIO_IO_HANDLE_NONE;
1073 }
1074 }
1075 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001076 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001077 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001078 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001079 if (*output == AUDIO_IO_HANDLE_NONE) {
1080 return INVALID_OPERATION;
1081 }
Paul McLeanaa981192015-03-21 09:55:15 -07001082
François Gaffiec005e562018-11-06 15:04:49 +01001083 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001084 for (auto &outputDevice : outputDevices) {
1085 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1086 *selectedDeviceId = outputDevice->getId();
1087 break;
1088 }
1089 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001090
Eric Laurent8a1095a2019-11-08 14:44:16 -08001091 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1092 *outputType = API_OUTPUT_TELEPHONY_TX;
1093 } else {
1094 *outputType = API_OUTPUT_LEGACY;
1095 }
1096
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001097 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1098
1099 return NO_ERROR;
1100}
1101
1102status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1103 audio_io_handle_t *output,
1104 audio_session_t session,
1105 audio_stream_type_t *stream,
1106 uid_t uid,
1107 const audio_config_t *config,
1108 audio_output_flags_t *flags,
1109 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001110 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001111 std::vector<audio_io_handle_t> *secondaryOutputs,
1112 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113{
1114 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1115 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1116 return INVALID_OPERATION;
1117 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001118 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001119 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001120 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001121 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001122 const sp<DeviceDescriptor> requestedDevice =
1123 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1124
1125 // Prevent from storing invalid requested device id in clients
1126 const audio_port_handle_t sanitizedRequestedPortId =
1127 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1128 *selectedDeviceId = sanitizedRequestedPortId;
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001131 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001132 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001133 if (status != NO_ERROR) {
1134 return status;
1135 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001136 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001137 if (secondaryOutputs != nullptr) {
1138 for (auto &secondaryMix : secondaryMixes) {
1139 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1140 if (outputDesc != nullptr &&
1141 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1142 secondaryOutputs->push_back(outputDesc->mIoHandle);
1143 weakSecondaryOutputDescs.push_back(outputDesc);
1144 }
1145 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001146 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147
Eric Laurent8fc147b2018-07-22 19:13:55 -07001148 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001149 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001150 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001151 };
jiabin4ef93452019-09-10 14:29:54 -07001152 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001153
Eric Laurentc209fe42020-06-05 18:11:23 -07001154 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001155 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001157 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001158 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001159 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001161 std::move(weakSecondaryOutputDescs),
1162 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001163 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001164
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001165 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1166 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001167
Eric Laurente83b55d2014-11-14 10:06:21 -08001168 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001169}
1170
Eric Laurentc529cf62020-04-17 18:19:10 -07001171status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1172 audio_session_t session,
1173 const audio_config_t *config,
1174 audio_output_flags_t flags,
1175 const DeviceVector &devices,
1176 audio_io_handle_t *output) {
1177
1178 *output = AUDIO_IO_HANDLE_NONE;
1179
1180 // skip direct output selection if the request can obviously be attached to a mixed output
1181 // and not explicitly requested
1182 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1183 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1184 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1185 return NAME_NOT_FOUND;
1186 }
1187
1188 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1189 // This prevents creating an offloaded track and tearing it down immediately after start
1190 // when audioflinger detects there is an active non offloadable effect.
1191 // FIXME: We should check the audio session here but we do not have it in this context.
1192 // This may prevent offloading in rare situations where effects are left active by apps
1193 // in the background.
1194 sp<IOProfile> profile;
1195 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1196 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1197 profile = getProfileForOutput(
1198 devices, config->sample_rate, config->format, config->channel_mask,
1199 flags, true /* directOnly */);
1200 }
1201
1202 if (profile == nullptr) {
1203 return NAME_NOT_FOUND;
1204 }
1205
1206 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1207 for (size_t i = 0; i < mOutputs.size(); i++) {
1208 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1209 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1210 // reuse direct output if currently open by the same client
1211 // and configured with same parameters
1212 if ((config->sample_rate == desc->getSamplingRate()) &&
1213 (config->format == desc->getFormat()) &&
1214 (config->channel_mask == desc->getChannelMask()) &&
1215 (session == desc->mDirectClientSession)) {
1216 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001217 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001218 mOutputs.keyAt(i), session);
1219 *output = mOutputs.keyAt(i);
1220 return NO_ERROR;
1221 }
1222 }
1223 }
1224
1225 if (!profile->canOpenNewIo()) {
1226 return NAME_NOT_FOUND;
1227 }
1228
1229 sp<SwAudioOutputDescriptor> outputDesc =
1230 new SwAudioOutputDescriptor(profile, mpClientInterface);
1231
Michael Chan6fb34492020-12-08 15:44:49 +11001232 // An MSD patch may be using the only output stream that can service this request. Release
1233 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001234 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001235
1236 status_t status = outputDesc->open(config, devices, stream, flags, output);
1237
1238 // only accept an output with the requested parameters
1239 if (status != NO_ERROR ||
1240 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1241 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1242 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1243 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1244 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1245 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1246 config->channel_mask, outputDesc->getChannelMask());
1247 if (*output != AUDIO_IO_HANDLE_NONE) {
1248 outputDesc->close();
1249 }
1250 // fall back to mixer output if possible when the direct output could not be open
1251 if (audio_is_linear_pcm(config->format) &&
1252 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1253 return NAME_NOT_FOUND;
1254 }
1255 *output = AUDIO_IO_HANDLE_NONE;
1256 return BAD_VALUE;
1257 }
1258 outputDesc->mDirectOpenCount = 1;
1259 outputDesc->mDirectClientSession = session;
1260
1261 addOutput(*output, outputDesc);
1262 mPreviousOutputs = mOutputs;
1263 ALOGV("%s returns new direct output %d", __func__, *output);
1264 mpClientInterface->onAudioPortListUpdate();
1265 return NO_ERROR;
1266}
1267
François Gaffie11d30102018-11-02 16:09:09 +01001268audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1269 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001270 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001271 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001272 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001273 audio_output_flags_t *flags,
1274 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001275{
Andy Hungc88b0642018-04-27 15:42:35 -07001276 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001277
jiabine375d412019-02-26 12:54:53 -08001278 // Discard haptic channel mask when forcing muting haptic channels.
1279 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001280 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1281 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001282
Eric Laurente552edb2014-03-10 17:42:56 -07001283 // open a direct output if required by specified parameters
1284 //force direct flag if offload flag is set: offloading implies a direct output stream
1285 // and all common behaviors are driven by checking only the direct flag
1286 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001287 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1288 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001289 }
Nadav Bar766fb022018-01-07 12:18:03 +02001290 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1291 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001292 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001293 // only allow deep buffering for music stream type
1294 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001295 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001296 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001297 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001298 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1299 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001300 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001301 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001302 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001303 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001304 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001305 audio_is_linear_pcm(config->format) &&
1306 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001307 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001308 AUDIO_OUTPUT_FLAG_DIRECT);
1309 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001310 }
Eric Laurente552edb2014-03-10 17:42:56 -07001311
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 audio_config_t directConfig = *config;
1313 directConfig.channel_mask = channelMask;
1314 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1315 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001316 return output;
1317 }
1318
Eric Laurent14cbfca2016-03-17 09:42:16 -07001319 // A request for HW A/V sync cannot fallback to a mixed output because time
1320 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001321 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001322 return AUDIO_IO_HANDLE_NONE;
1323 }
1324
Eric Laurente552edb2014-03-10 17:42:56 -07001325 // ignoring channel mask due to downmix capability in mixer
1326
1327 // open a non direct output
1328
1329 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001330 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001331 // get which output is suitable for the specified stream. The actual
1332 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001333 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001334
Eric Laurent8838a382014-09-08 16:44:28 -07001335 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001336 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001337 output = selectOutput(
1338 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
François Gaffie11d30102018-11-02 16:09:09 +01001340 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001341 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001342 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001343
Eric Laurente552edb2014-03-10 17:42:56 -07001344 return output;
1345}
1346
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001347sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001348 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1349 mAvailableInputDevices);
1350 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1351}
1352
1353DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1354 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1355 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001356}
1357
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001358const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001359 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001360 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1361 if (msdModule != 0) {
1362 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1363 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1364 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1365 const struct audio_port_config *source = &patch->mPatch.sources[j];
1366 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1367 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001368 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001369 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001370 }
1371 }
1372 }
1373 return msdPatches;
1374}
1375
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001376status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1377 const InputProfileCollection &inputProfiles,
1378 const OutputProfileCollection &outputProfiles,
1379 const sp<DeviceDescriptor> &sourceDevice,
1380 const sp<DeviceDescriptor> &sinkDevice,
1381 AudioProfileVector& sourceProfiles,
1382 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001384 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001385 return NO_INIT;
1386 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001388 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001389 return NO_INIT;
1390 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001391 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001392 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1393 inProfile->supportsDevice(sourceDevice)) {
1394 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001395 }
1396 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001397 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001398 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001399 outProfile->supportsDevice(sinkDevice)) {
1400 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001401 }
1402 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001403 return NO_ERROR;
1404}
1405
1406status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1407 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1408 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1409{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001411 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1412 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1413 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001414 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001415 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1416 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001417 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 }
1419 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1420 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1421 sinkConfig->format = bestSinkConfig.format;
1422 // For encoded streams force direct flag to prevent downstream mixing.
1423 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1424 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001425 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1426 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001427 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001428 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1429 // raw and IEC61937 framed streams.
1430 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1431 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1432 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001433 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1434 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1435 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1436 sourceConfig->format = bestSinkConfig.format;
1437 // Copy input stream directly without any processing (e.g. resampling).
1438 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1439 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1440 if (hwAvSync) {
1441 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1442 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1443 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1444 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1445 }
1446 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1447 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1448 sinkConfig->config_mask |= config_mask;
1449 sourceConfig->config_mask |= config_mask;
1450 return NO_ERROR;
1451}
1452
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001453PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1454 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001455{
1456 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001457 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1458 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1459 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1460 if (deviceModule == nullptr) {
1461 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1462 return patchBuilder;
1463 }
1464 const InputProfileCollection inputProfiles = msdIsSource ?
1465 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1466 const OutputProfileCollection outputProfiles = msdIsSource ?
1467 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1468
1469 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1470 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1471 device : getMsdAudioOutDevices().itemAt(0);
1472 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1473
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1475 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001476 AudioProfileVector sourceProfiles;
1477 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001478 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1479 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001480 for (auto hwAvSync : { true, false }) {
1481 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1482 sourceProfiles, sinkProfiles) != NO_ERROR) {
1483 continue;
1484 }
1485 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1486 &sinkConfig) == NO_ERROR) {
1487 // Found a matching config. Re-create PatchBuilder with this config.
1488 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1489 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001490 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001491 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001492 " supporting PCM format conversion.", __func__);
1493 return patchBuilder;
1494}
1495
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001496status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001497 DeviceVector devices;
1498 if (outputDevices != nullptr && outputDevices->size() > 0) {
1499 devices.add(*outputDevices);
1500 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001501 // Use media strategy for unspecified output device. This should only
1502 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1503 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001504 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001505 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001506 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001507 }
Michael Chan6fb34492020-12-08 15:44:49 +11001508 std::vector<PatchBuilder> patchesToCreate;
1509 for (auto i = 0u; i < devices.size(); ++i) {
1510 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001511 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001512 }
1513 // Retain only the MSD patches associated with outputDevices request.
1514 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001515 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001516 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1517 auto retainedPatch = false;
1518 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1519 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1520 patchesToRemove.removeItemsAt(i);
1521 retainedPatch = true;
1522 break;
1523 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001524 }
Michael Chan6fb34492020-12-08 15:44:49 +11001525 if (retainedPatch) {
1526 it = patchesToCreate.erase(it);
1527 continue;
1528 }
1529 ++it;
1530 }
1531 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1532 return NO_ERROR;
1533 }
1534 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1535 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001536 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537 }
Michael Chan6fb34492020-12-08 15:44:49 +11001538 status_t status = NO_ERROR;
1539 for (const auto &p : patchesToCreate) {
1540 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1541 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1542 char message[256];
1543 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1544 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1545 currStatus == NO_ERROR ? "Success" : "Error",
1546 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1547 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1548 if (currStatus == NO_ERROR) {
1549 ALOGD("%s", message);
1550 } else {
1551 ALOGE("%s", message);
1552 if (status == NO_ERROR) {
1553 status = currStatus;
1554 }
1555 }
1556 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001557 return status;
1558}
1559
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001560void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1561 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001562 for (size_t i = 0; i < msdPatches.size(); i++) {
1563 const auto& patch = msdPatches[i];
1564 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1565 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1566 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1567 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1568 releaseAudioPatch(patch->getHandle(), mUidCached);
1569 break;
1570 }
1571 }
1572 }
1573}
1574
Eric Laurente0720872014-03-11 09:30:41 -07001575audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001576 audio_output_flags_t flags,
1577 audio_format_t format,
1578 audio_channel_mask_t channelMask,
1579 uint32_t samplingRate,
1580 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001581{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001582 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1583 "%s called with format %#x", __func__, format);
1584
jiabinebb6af42020-06-09 17:31:17 -07001585 // Return the output that haptic-generating attached to when 1) session id is specified,
1586 // 2) haptic-generating effect exists for given session id and 3) the output that
1587 // haptic-generating effect attached to is in given outputs.
1588 if (sessionId != AUDIO_SESSION_NONE) {
1589 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1590 sessionId, FX_IID_HAPTICGENERATOR);
1591 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1592 return hapticGeneratingOutput;
1593 }
1594 }
1595
Eric Laurent16c66dd2019-05-01 17:54:10 -07001596 // Flags disqualifying an output: the match must happen before calling selectOutput()
1597 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1598 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1599
1600 // Flags expressing a functional request: must be honored in priority over
1601 // other criteria
1602 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1603 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1604 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1605 // Flags expressing a performance request: have lower priority than serving
1606 // requested sampling rate or channel mask
1607 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1608 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1609 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1610
1611 const audio_output_flags_t functionalFlags =
1612 (audio_output_flags_t)(flags & kFunctionalFlags);
1613 const audio_output_flags_t performanceFlags =
1614 (audio_output_flags_t)(flags & kPerformanceFlags);
1615
1616 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1617
Eric Laurente552edb2014-03-10 17:42:56 -07001618 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001619 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001620 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001621 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001622 // 2: the output with the highest number of requested functional flags
1623 // 3: the output supporting the exact channel mask
1624 // 4: the output with a higher channel count than requested
1625 // 5: the output with a higher sampling rate than requested
1626 // 6: the output with the highest number of requested performance flags
1627 // 7: the output with the bit depth the closest to the requested one
1628 // 8: the primary output
1629 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001630
Eric Laurent16c66dd2019-05-01 17:54:10 -07001631 // matching criteria values in priority order for best matching output so far
1632 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Eric Laurent16c66dd2019-05-01 17:54:10 -07001634 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1635 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1636 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001637
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001638 for (audio_io_handle_t output : outputs) {
1639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001640 // matching criteria values in priority order for current output
1641 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001642
Eric Laurent16c66dd2019-05-01 17:54:10 -07001643 if (outputDesc->isDuplicated()) {
1644 continue;
1645 }
1646 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1647 continue;
1648 }
Eric Laurent8838a382014-09-08 16:44:28 -07001649
Eric Laurent16c66dd2019-05-01 17:54:10 -07001650 // If haptic channel is specified, use the haptic output if present.
1651 // When using haptic output, same audio format and sample rate are required.
1652 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001653 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001654 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1655 continue;
1656 }
1657 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001658 && format == outputDesc->getFormat()
1659 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001660 currentMatchCriteria[0] = outputHapticChannelCount;
1661 }
1662
1663 // functional flags match
1664 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1665
1666 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001667 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1668 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001669 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1670 channelCount <= outputChannelCount) {
1671 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001672 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1673 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001674 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001675 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001676 currentMatchCriteria[3] = outputChannelCount;
1677 }
1678
1679 // sampling rate match
1680 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001681 samplingRate <= outputDesc->getSamplingRate()) {
1682 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001683 }
1684
1685 // performance flags match
1686 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1687
1688 // format match
1689 if (format != AUDIO_FORMAT_INVALID) {
1690 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001691 PolicyAudioPort::kFormatDistanceMax -
1692 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 }
1694
1695 // primary output match
1696 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1697
1698 // compare match criteria by priority then value
1699 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1700 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1701 bestMatchCriteria = currentMatchCriteria;
1702 bestOutput = output;
1703
1704 std::stringstream result;
1705 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1706 std::ostream_iterator<int>(result, " "));
1707 ALOGV("%s new bestOutput %d criteria %s",
1708 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001709 }
1710 }
1711
Eric Laurent16c66dd2019-05-01 17:54:10 -07001712 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001713}
1714
Eric Laurent8fc147b2018-07-22 19:13:55 -07001715status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001716{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001717 ALOGV("%s portId %d", __FUNCTION__, portId);
1718
1719 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1720 if (outputDesc == 0) {
1721 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001722 return BAD_VALUE;
1723 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001724 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001725
Eric Laurent8fc147b2018-07-22 19:13:55 -07001726 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001727 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001728
Eric Laurent733ce942017-12-07 12:18:25 -08001729 status_t status = outputDesc->start();
1730 if (status != NO_ERROR) {
1731 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001732 }
1733
Eric Laurent97ac8712018-07-27 18:59:02 -07001734 uint32_t delayMs;
1735 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001736
1737 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001738 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001739 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001740 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001741 if (delayMs != 0) {
1742 usleep(delayMs * 1000);
1743 }
1744
1745 return status;
1746}
1747
Eric Laurent97ac8712018-07-27 18:59:02 -07001748status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1749 const sp<TrackClientDescriptor>& client,
1750 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001751{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001752 // cannot start playback of STREAM_TTS if any other output is being used
1753 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001754
1755 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001756 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001757 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001758 auto clientStrategy = client->strategy();
1759 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001760 if (stream == AUDIO_STREAM_TTS) {
1761 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001762 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001763 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001764 return INVALID_OPERATION;
1765 } else {
1766 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1767 }
1768 } else {
1769 // some playback other than beacon starts
1770 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1771 }
1772
Eric Laurent77305a62016-07-25 16:39:22 -07001773 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001774 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001775 bool force = !outputDesc->isActive() &&
1776 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001777
François Gaffie11d30102018-11-02 16:09:09 +01001778 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001779 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001780 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001781 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001782 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001783 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001784 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001785 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001786 } else {
1787 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001788 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001789 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1790 AUDIO_FORMAT_DEFAULT);
1791 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1792 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001793 }
1794
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001795 // requiresMuteCheck is false when we can bypass mute strategy.
1796 // It covers a common case when there is no materially active audio
1797 // and muting would result in unnecessary delay and dropped audio.
1798 const uint32_t outputLatencyMs = outputDesc->latency();
1799 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1800
Eric Laurente552edb2014-03-10 17:42:56 -07001801 // increment usage count for this stream on the requested output:
1802 // NOTE that the usage count is the same for duplicated output and hardware output which is
1803 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001804 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001805
1806 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001807 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1808 client->isPreferredDeviceForExclusiveUse()) {
1809 // Preferred device may be exclusive, use only if no other active clients on this output
1810 devices = DeviceVector(
1811 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1812 } else {
1813 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1814 }
François Gaffie11d30102018-11-02 16:09:09 +01001815 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001816 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001817 }
1818 }
Eric Laurente552edb2014-03-10 17:42:56 -07001819
François Gaffiec005e562018-11-06 15:04:49 +01001820 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001821 selectOutputForMusicEffects();
1822 }
1823
François Gaffie1c878552018-11-22 16:53:21 +01001824 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001825 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001826 if (devices.isEmpty()) {
1827 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001828 }
François Gaffiec005e562018-11-06 15:04:49 +01001829 bool shouldWait =
1830 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1831 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1832 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001833 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001834 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001835 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001836 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001837 // An output has a shared device if
1838 // - managed by the same hw module
1839 // - supports the currently selected device
1840 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001841 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001842
Eric Laurent77305a62016-07-25 16:39:22 -07001843 // force a device change if any other output is:
1844 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001845 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001846 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001847 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001848 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001849 // change the device currently selected by the other output.
1850 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001851 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001852 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001853 force = true;
1854 }
1855 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001856 // a notification so that audio focus effect can propagate, or that a mute/unmute
1857 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001858 const uint32_t latencyMs = desc->latency();
1859 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1860
1861 if (shouldWait && isActive && (waitMs < latencyMs)) {
1862 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001863 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001864
1865 // Require mute check if another output is on a shared device
1866 // and currently active to have proper drain and avoid pops.
1867 // Note restoring AudioTracks onto this output needs to invoke
1868 // a volume ramp if there is no mute.
1869 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001870 }
1871 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001872
1873 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001874 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001875
Eric Laurente552edb2014-03-10 17:42:56 -07001876 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001877 auto &curves = getVolumeCurves(client->attributes());
1878 checkAndSetVolume(curves, client->volumeSource(),
1879 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001880 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001881 outputDesc->devices().types(), 0 /*delay*/,
1882 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001883
1884 // update the outputs if starting an output with a stream that can affect notification
1885 // routing
1886 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001887
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001888 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001889 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001890 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1891 }
Eric Laurentdc462862016-07-19 12:29:53 -07001892
1893 if (waitMs > muteWaitMs) {
1894 *delayMs = waitMs - muteWaitMs;
1895 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001896
1897 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1898 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1899 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1900 // change occurs after the MixerThread starts and causes a stream volume
1901 // glitch.
1902 //
1903 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001904 }
Eric Laurentdc462862016-07-19 12:29:53 -07001905
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001906 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001907 mEngine->getForceUse(
1908 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001909 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001910 }
1911
Eric Laurent97ac8712018-07-27 18:59:02 -07001912 // Automatically enable the remote submix input when output is started on a re routing mix
1913 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001914 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1915 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001916 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1917 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1918 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001919 "remote-submix",
1920 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001921 }
1922
Eric Laurente552edb2014-03-10 17:42:56 -07001923 return NO_ERROR;
1924}
1925
Eric Laurent8fc147b2018-07-22 19:13:55 -07001926status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001927{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001928 ALOGV("%s portId %d", __FUNCTION__, portId);
1929
1930 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1931 if (outputDesc == 0) {
1932 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001933 return BAD_VALUE;
1934 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001935 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001936
Eric Laurent97ac8712018-07-27 18:59:02 -07001937 ALOGV("stopOutput() output %d, stream %d, session %d",
1938 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001939
Eric Laurent97ac8712018-07-27 18:59:02 -07001940 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001941
Eric Laurent733ce942017-12-07 12:18:25 -08001942 if (status == NO_ERROR ) {
1943 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001944 }
1945 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001946}
1947
Eric Laurent97ac8712018-07-27 18:59:02 -07001948status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1949 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001950{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001951 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001952 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001953 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001954
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001955 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1956
François Gaffie1c878552018-11-22 16:53:21 +01001957 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1958 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001959 // Automatically disable the remote submix input when output is stopped on a
1960 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001961 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001962 if (isSingleDeviceType(
1963 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001964 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001965 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001966 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1967 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001968 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001969 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001970 }
1971 }
1972 bool forceDeviceUpdate = false;
1973 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001974 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001975 forceDeviceUpdate = true;
1976 }
1977
Eric Laurente552edb2014-03-10 17:42:56 -07001978 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001979 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001980
Eric Laurente552edb2014-03-10 17:42:56 -07001981 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001982 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001983 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001984 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001985 // delay the device switch by twice the latency because stopOutput() is executed when
1986 // the track stop() command is received and at that time the audio track buffer can
1987 // still contain data that needs to be drained. The latency only covers the audio HAL
1988 // and kernel buffers. Also the latency does not always include additional delay in the
1989 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001990 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001991
1992 // force restoring the device selection on other active outputs if it differs from the
1993 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001994 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001995 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001996 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001997 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001998 desc->isActive() &&
1999 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002000 (newDevices != desc->devices())) {
2001 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2002 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002003
François Gaffie11d30102018-11-02 16:09:09 +01002004 setOutputDevices(desc, newDevices2, force, delayMs);
2005
Eric Laurent57de36c2016-09-28 16:59:11 -07002006 // re-apply device specific volume if not done by setOutputDevice()
2007 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002008 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002009 }
Eric Laurente552edb2014-03-10 17:42:56 -07002010 }
2011 }
2012 // update the outputs if stopping one with a stream that can affect notification routing
2013 handleNotificationRoutingForStream(stream);
2014 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002015
2016 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2017 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002018 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002019 }
2020
François Gaffiec005e562018-11-06 15:04:49 +01002021 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002022 selectOutputForMusicEffects();
2023 }
Eric Laurente552edb2014-03-10 17:42:56 -07002024 return NO_ERROR;
2025 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002026 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002027 return INVALID_OPERATION;
2028 }
2029}
2030
jiabinbce0c1d2020-10-05 11:20:18 -07002031bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002032{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002033 ALOGV("%s portId %d", __FUNCTION__, portId);
2034
2035 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2036 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002037 // If an output descriptor is closed due to a device routing change,
2038 // then there are race conditions with releaseOutput from tracks
2039 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2040 // destroyed shortly thereafter.
2041 //
2042 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002043 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002044 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002045 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002046
2047 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002048
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302049 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2050 if (outputDesc->isClientActive(client)) {
2051 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2052 stopOutput(portId);
2053 }
2054
Eric Laurent8fc147b2018-07-22 19:13:55 -07002055 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2056 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002057 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002058 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002059 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002060 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002061 if (--outputDesc->mDirectOpenCount == 0) {
2062 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002063 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002064 }
2065 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302066
Andy Hung39efb7a2018-09-26 15:39:28 -07002067 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002068 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2069 // The output is pending reopened to query dynamic profiles and
2070 // there is no active clients
2071 closeOutput(outputDesc->mIoHandle);
2072 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2073 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2074 if (newOutputDesc == nullptr) {
2075 ALOGE("%s failed to open output", __func__);
2076 }
2077 return true;
2078 }
2079 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002080}
2081
Eric Laurentcaf7f482014-11-25 17:50:47 -08002082status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2083 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002084 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002085 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002086 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002087 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002088 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002089 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002090 input_type_t *inputType,
2091 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002092{
François Gaffiec005e562018-11-06 15:04:49 +01002093 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2094 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2095 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002096
Eric Laurentad2e7b92017-09-14 20:06:42 -07002097 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002098 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002099 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002100 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002101 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 sp<AudioInputDescriptor> inputDesc;
2103 sp<RecordClientDescriptor> clientDesc;
2104 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002105 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106
2107 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2108 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2109 return INVALID_OPERATION;
2110 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002111
Francois Gaffie716e1432019-01-14 16:58:59 +01002112 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2113 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002114 }
2115
Paul McLean466dc8e2015-04-17 13:15:36 -06002116 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002117 sp<DeviceDescriptor> explicitRoutingDevice =
2118 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002119
Eric Laurentad2e7b92017-09-14 20:06:42 -07002120 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2121 // possible
2122 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2123 *input != AUDIO_IO_HANDLE_NONE) {
2124 ssize_t index = mInputs.indexOfKey(*input);
2125 if (index < 0) {
2126 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2127 status = BAD_VALUE;
2128 goto error;
2129 }
2130 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 RecordClientVector clients = inputDesc->getClientsForSession(session);
2132 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002133 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2134 status = BAD_VALUE;
2135 goto error;
2136 }
2137 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2138 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002139 // corresponds to a new client and is only permitted from the same UID.
2140 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002141 if (clients.size() > 1) {
2142 for (const auto& client : clients) {
2143 // The client map is ordered by key values (portId) and portIds are allocated
2144 // incrementaly. So the first client in this list is the one opened by audio flinger
2145 // when the mmap stream is created and should be ignored as it does not correspond
2146 // to an actual client
2147 if (client == *clients.cbegin()) {
2148 continue;
2149 }
2150 if (uid != client->uid() && !client->isSilenced()) {
2151 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2152 uid, client->portId(), client->uid());
2153 status = INVALID_OPERATION;
2154 goto error;
2155 }
Eric Laurent331679c2018-04-16 17:03:16 -07002156 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002157 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002158 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002159 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002160
Eric Laurentfecbceb2021-02-09 14:46:43 +01002161 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002162 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002163 }
2164
2165 *input = AUDIO_IO_HANDLE_NONE;
2166 *inputType = API_INPUT_INVALID;
2167
Francois Gaffie716e1432019-01-14 16:58:59 +01002168 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002169
Francois Gaffie716e1432019-01-14 16:58:59 +01002170 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2171 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2172 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002173 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002174 ALOGW("%s could not find input mix for attr %s",
2175 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002176 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002177 }
jiabinc1de2df2019-05-07 14:26:40 -07002178 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2179 String8(attr->tags + strlen("addr=")),
2180 AUDIO_FORMAT_DEFAULT);
2181 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002182 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002183 __func__, attributes.source, attributes.tags);
2184 status = BAD_VALUE;
2185 goto error;
2186 }
2187
Kevin Rocard25f9b052019-02-27 15:08:54 -08002188 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2189 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2190 } else {
2191 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2192 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002193 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002194 if (explicitRoutingDevice != nullptr) {
2195 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002197 // Prevent from storing invalid requested device id in clients
2198 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002199 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002200 }
François Gaffie11d30102018-11-02 16:09:09 +01002201 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002202 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002203 status = BAD_VALUE;
2204 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002205 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002206 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2207 *inputType = API_INPUT_MIX_CAPTURE;
2208 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002209 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2210 // there is an external policy, but this input is attached to a mix of recorders,
2211 // meaning it receives audio injected into the framework, so the recorder doesn't
2212 // know about it and is therefore considered "legacy"
2213 *inputType = API_INPUT_LEGACY;
2214 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002215 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002216 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002217 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002218 } else {
2219 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002220 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002221
Eric Laurent599c7582015-12-07 18:05:55 -08002222 }
2223
François Gaffiec005e562018-11-06 15:04:49 +01002224 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002225 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002226 status = INVALID_OPERATION;
2227 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002228 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002229
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230exit:
2231
François Gaffiec005e562018-11-06 15:04:49 +01002232 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2233 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002234
Francois Gaffie716e1432019-01-14 16:58:59 +01002235 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002236 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002237 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002238
Mikhail Naganov2996f672019-04-18 12:29:59 -07002239 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002240 requestedDeviceId, attributes.source, flags,
2241 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002243 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002244
2245 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2246 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002247
Eric Laurent599c7582015-12-07 18:05:55 -08002248 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002249
2250error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002251 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002252}
2253
2254
François Gaffie11d30102018-11-02 16:09:09 +01002255audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002256 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002257 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002258 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002259 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002260 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002261{
2262 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002263 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002264 bool isSoundTrigger = false;
2265
François Gaffiec005e562018-11-06 15:04:49 +01002266 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002267 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2268 if (index >= 0) {
2269 input = mSoundTriggerSessions.valueFor(session);
2270 isSoundTrigger = true;
2271 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2272 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2273 } else {
2274 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002275 }
François Gaffiec005e562018-11-06 15:04:49 +01002276 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002277 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002278 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002279 }
2280
Andy Hungf129b032015-04-07 13:45:50 -07002281 // find a compatible input profile (not necessarily identical in parameters)
2282 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002283 // sampling rate and flags may be updated by getInputProfile
2284 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2285 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002286 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002287 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002288 audio_input_flags_t profileFlags = flags;
2289 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002290 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002291 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002292 profileFlags);
2293 if (profile != 0) {
2294 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002295 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2296 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002297 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2298 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2299 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002300 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2301 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2302 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002303 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002304 }
Eric Laurente552edb2014-03-10 17:42:56 -07002305 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002306 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002307 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002308 if (samplingRate == 0) {
2309 samplingRate = profileSamplingRate;
2310 }
Eric Laurente552edb2014-03-10 17:42:56 -07002311
Eric Laurent322b4d22015-04-03 15:57:54 -07002312 if (profile->getModuleHandle() == 0) {
2313 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002314 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002315 }
2316
Eric Laurent3974e3b2017-12-07 17:58:43 -08002317 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002318 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002319 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002320 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002321 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002322 continue;
2323 }
2324 // if sound trigger, reuse input if used by other sound trigger on same session
2325 // else
2326 // reuse input if active client app is not in IDLE state
2327 //
2328 RecordClientVector clients = desc->clientsList();
2329 bool doClose = false;
2330 for (const auto& client : clients) {
2331 if (isSoundTrigger != client->isSoundTrigger()) {
2332 continue;
2333 }
2334 if (client->isSoundTrigger()) {
2335 if (session == client->session()) {
2336 return desc->mIoHandle;
2337 }
2338 continue;
2339 }
2340 if (client->active() && client->appState() != APP_STATE_IDLE) {
2341 return desc->mIoHandle;
2342 }
2343 doClose = true;
2344 }
2345 if (doClose) {
2346 closeInput(desc->mIoHandle);
2347 } else {
2348 i++;
2349 }
2350 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002351 }
2352
Eric Laurentfe231122017-11-17 17:48:06 -08002353 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002354
Eric Laurentfe231122017-11-17 17:48:06 -08002355 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2356 lConfig.sample_rate = profileSamplingRate;
2357 lConfig.channel_mask = profileChannelMask;
2358 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002359
François Gaffie11d30102018-11-02 16:09:09 +01002360 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002361
2362 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002363 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002364 (profileSamplingRate != lConfig.sample_rate) ||
2365 !audio_formats_match(profileFormat, lConfig.format) ||
2366 (profileChannelMask != lConfig.channel_mask)) {
2367 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002368 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002369 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002370 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002371 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002372 }
Eric Laurent599c7582015-12-07 18:05:55 -08002373 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002374 }
2375
Eric Laurentc722f302014-12-10 11:21:49 -08002376 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002377
Eric Laurent599c7582015-12-07 18:05:55 -08002378 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002379 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002380
Eric Laurent599c7582015-12-07 18:05:55 -08002381 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002382}
2383
Eric Laurent4eb58f12018-12-07 16:41:02 -08002384status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002385{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002386 ALOGV("%s portId %d", __FUNCTION__, portId);
2387
2388 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2389 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002390 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002391 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002392 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002393 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002394 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002395 if (client->active()) {
2396 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2397 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002398 }
2399
Eric Laurent8f42ea12018-08-08 09:08:25 -07002400 audio_session_t session = client->session();
2401
Eric Laurent4eb58f12018-12-07 16:41:02 -08002402 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002403
Eric Laurent4eb58f12018-12-07 16:41:02 -08002404 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002405
Eric Laurent4eb58f12018-12-07 16:41:02 -08002406 status_t status = inputDesc->start();
2407 if (status != NO_ERROR) {
2408 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002409 }
Eric Laurente552edb2014-03-10 17:42:56 -07002410
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002411 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002412 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002413 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002414
Eric Laurent8f42ea12018-08-08 09:08:25 -07002415 // indicate active capture to sound trigger service if starting capture from a mic on
2416 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002417 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002418 if (device != nullptr) {
2419 status = setInputDevice(input, device, true /* force */);
2420 } else {
2421 ALOGW("%s no new input device can be found for descriptor %d",
2422 __FUNCTION__, inputDesc->getId());
2423 status = BAD_VALUE;
2424 }
Eric Laurente552edb2014-03-10 17:42:56 -07002425
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002426 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002427 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002428 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002429 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002430 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2431 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002432 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002433 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002434
François Gaffie11d30102018-11-02 16:09:09 +01002435 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2436 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002437 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002438 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002439 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002440
Eric Laurent8f42ea12018-08-08 09:08:25 -07002441 // automatically enable the remote submix output when input is started if not
2442 // used by a policy mix of type MIX_TYPE_RECORDERS
2443 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002444 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002445 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002446 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002447 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002448 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2449 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002450 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002451 if (address != "") {
2452 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2453 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002454 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002455 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002456 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002457 } else if (status != NO_ERROR) {
2458 // Restore client activity state.
2459 inputDesc->setClientActive(client, false);
2460 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002461 }
2462
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002463 ALOGV("%s input %d source = %d status = %d exit",
2464 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002465
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002466 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002467}
2468
Eric Laurent8fc147b2018-07-22 19:13:55 -07002469status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002470{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002471 ALOGV("%s portId %d", __FUNCTION__, portId);
2472
2473 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2474 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002476 return BAD_VALUE;
2477 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002478 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002479 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002480 if (!client->active()) {
2481 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002482 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002483 }
2484
Eric Laurent8f42ea12018-08-08 09:08:25 -07002485 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002486
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 inputDesc->stop();
2488 if (inputDesc->isActive()) {
2489 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2490 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002491 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002493 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002494 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2495 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002496 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002497 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002498
2499 // automatically disable the remote submix output when input is stopped if not
2500 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002501 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002503 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002504 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002505 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2506 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002507 }
2508 if (address != "") {
2509 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2510 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002511 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002512 }
2513 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 resetInputDevice(input);
2515
2516 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2517 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002518 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2519 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002520 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002521 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002522 }
2523 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002524 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002525 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002526}
2527
Eric Laurent8fc147b2018-07-22 19:13:55 -07002528void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002529{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002530 ALOGV("%s portId %d", __FUNCTION__, portId);
2531
2532 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2533 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002534 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002535 return;
2536 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002537 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002538 audio_io_handle_t input = inputDesc->mIoHandle;
2539
Eric Laurent8f42ea12018-08-08 09:08:25 -07002540 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002541
Andy Hung39efb7a2018-09-26 15:39:28 -07002542 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002543
Andy Hung39efb7a2018-09-26 15:39:28 -07002544 if (inputDesc->getClientCount() > 0) {
2545 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002546 return;
2547 }
2548
Eric Laurent05b90f82014-08-27 15:32:29 -07002549 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002550 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002551 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002552}
2553
Eric Laurent8f42ea12018-08-08 09:08:25 -07002554void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002555{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002557
2558 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002559 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002560 }
2561}
2562
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2564{
2565 stopInput(portId);
2566 releaseInput(portId);
2567}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002568
Eric Laurent0dd51852019-04-19 18:18:58 -07002569void AudioPolicyManager::checkCloseInputs() {
2570 // After connecting or disconnecting an input device, close input if:
2571 // - it has no client (was just opened to check profile) OR
2572 // - none of its supported devices are connected anymore OR
2573 // - one of its clients cannot be routed to one of its supported
2574 // devices anymore. Otherwise update device selection
2575 std::vector<audio_io_handle_t> inputsToClose;
2576 for (size_t i = 0; i < mInputs.size(); i++) {
2577 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2578 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002579 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002580 inputsToClose.push_back(mInputs.keyAt(i));
2581 } else {
2582 bool close = false;
2583 for (const auto& client : input->clientsList()) {
2584 sp<DeviceDescriptor> device =
2585 mEngine->getInputDeviceForAttributes(client->attributes());
2586 if (!input->supportedDevices().contains(device)) {
2587 close = true;
2588 break;
2589 }
2590 }
2591 if (close) {
2592 inputsToClose.push_back(mInputs.keyAt(i));
2593 } else {
2594 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2595 }
2596 }
2597 }
2598
2599 for (const audio_io_handle_t handle : inputsToClose) {
2600 ALOGV("%s closing input %d", __func__, handle);
2601 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002602 }
Eric Laurentd4692962014-05-05 18:13:44 -07002603}
2604
François Gaffie251c7f02018-11-07 10:41:08 +01002605void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002606{
2607 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002608 if (indexMin < 0 || indexMax < 0) {
2609 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2610 return;
2611 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002612 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002613
2614 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002615 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2616 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002617 continue;
2618 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002619 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002620 }
Eric Laurente552edb2014-03-10 17:42:56 -07002621}
2622
Eric Laurente0720872014-03-11 09:30:41 -07002623status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002624 int index,
2625 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002626{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002627 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002628 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2629 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2630 return NO_ERROR;
2631 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002632 ALOGV("%s: stream %s attributes=%s", __func__,
2633 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002634 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002635}
2636
Eric Laurente0720872014-03-11 09:30:41 -07002637status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002638 int *index,
2639 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002640{
François Gaffiec005e562018-11-06 15:04:49 +01002641 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2642 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002643 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002644 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002645 deviceTypes = mEngine->getOutputDevicesForStream(
2646 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002647 }
jiabin9a3361e2019-10-01 09:38:30 -07002648 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002649}
2650
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002651status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002652 int index,
2653 audio_devices_t device)
2654{
2655 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002656 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2657 if (group == VOLUME_GROUP_NONE) {
2658 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002659 return BAD_VALUE;
2660 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002661 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002662 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002663 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002664 VolumeSource vs = toVolumeSource(group);
2665 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2666
2667 status = setVolumeCurveIndex(index, device, curves);
2668 if (status != NO_ERROR) {
2669 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2670 return status;
2671 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002672
jiabin9a3361e2019-10-01 09:38:30 -07002673 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002674 auto curCurvAttrs = curves.getAttributes();
2675 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2676 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002677 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002678 } else if (!curves.getStreamTypes().empty()) {
2679 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002680 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002681 } else {
2682 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2683 return BAD_VALUE;
2684 }
jiabin9a3361e2019-10-01 09:38:30 -07002685 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2686 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002687
François Gaffiecfe17322018-11-07 13:41:29 +01002688 // update volume on all outputs and streams matching the following:
2689 // - The requested stream (or a stream matching for volume control) is active on the output
2690 // - The device (or devices) selected by the engine for this stream includes
2691 // the requested device
2692 // - For non default requested device, currently selected device on the output is either the
2693 // requested device or one of the devices selected by the engine for this stream
2694 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2695 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002696 for (size_t i = 0; i < mOutputs.size(); i++) {
2697 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002698 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002699
jiabin9a3361e2019-10-01 09:38:30 -07002700 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2701 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002702 }
François Gaffieed91f582020-01-31 10:35:37 +01002703 if (!(desc->isActive(vs) || isInCall())) {
2704 continue;
2705 }
2706 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2707 curDevices.find(device) == curDevices.end()) {
2708 continue;
2709 }
2710 bool applyVolume = false;
2711 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2712 curSrcDevices.insert(device);
2713 applyVolume = (curSrcDevices.find(
2714 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2715 } else {
2716 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2717 }
2718 if (!applyVolume) {
2719 continue; // next output
2720 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002721 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2722 // If a higher priority strategy is active, and the output is routed to a device with a
2723 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002724 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002725 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002726 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2727 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2728 false /*preferredDevice*/);
2729 if (activeClients.empty()) {
2730 continue;
2731 }
2732 bool isPreempted = false;
2733 bool isHigherPriority = productStrategy < strategy;
2734 for (const auto &client : activeClients) {
2735 if (isHigherPriority && (client->volumeSource() != vs)) {
2736 ALOGV("%s: Strategy=%d (\nrequester:\n"
2737 " group %d, volumeGroup=%d attributes=%s)\n"
2738 " higher priority source active:\n"
2739 " volumeGroup=%d attributes=%s) \n"
2740 " on output %zu, bailing out", __func__, productStrategy,
2741 group, group, toString(attributes).c_str(),
2742 client->volumeSource(), toString(client->attributes()).c_str(), i);
2743 applyVolume = false;
2744 isPreempted = true;
2745 break;
2746 }
2747 // However, continue for loop to ensure no higher prio clients running on output
2748 if (client->volumeSource() == vs) {
2749 applyVolume = true;
2750 }
2751 }
2752 if (isPreempted || applyVolume) {
2753 break;
2754 }
2755 }
2756 if (!applyVolume) {
2757 continue; // next output
2758 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002759 }
François Gaffieed91f582020-01-31 10:35:37 +01002760 //FIXME: workaround for truncated touch sounds
2761 // delayed volume change for system stream to be removed when the problem is
2762 // handled by system UI
2763 status_t volStatus = checkAndSetVolume(
2764 curves, vs, index, desc, curDevices,
2765 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2766 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2767 if (volStatus != NO_ERROR) {
2768 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002769 }
2770 }
François Gaffiecfe17322018-11-07 13:41:29 +01002771 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2772 return status;
2773}
2774
François Gaffieaaac0fd2018-11-22 17:56:39 +01002775status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002776 audio_devices_t device,
2777 IVolumeCurves &volumeCurves)
2778{
2779 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2780 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002781 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2782 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002783 (index > volumeCurves.getVolumeIndexMax())) {
2784 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2785 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2786 return BAD_VALUE;
2787 }
2788 if (!audio_is_output_device(device)) {
2789 return BAD_VALUE;
2790 }
2791
2792 // Force max volume if stream cannot be muted
2793 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2794
François Gaffieaaac0fd2018-11-22 17:56:39 +01002795 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002796 volumeCurves.addCurrentVolumeIndex(device, index);
2797 return NO_ERROR;
2798}
2799
2800status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2801 int &index,
2802 audio_devices_t device)
2803{
2804 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2805 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002806 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002807 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002808 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2809 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002810 }
jiabin9a3361e2019-10-01 09:38:30 -07002811 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002812}
2813
2814status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2815 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002816 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002817{
jiabin9a3361e2019-10-01 09:38:30 -07002818 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002819 return BAD_VALUE;
2820 }
jiabin9a3361e2019-10-01 09:38:30 -07002821 index = curves.getVolumeIndex(deviceTypes);
2822 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002823 return NO_ERROR;
2824}
2825
2826status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2827 int &index)
2828{
2829 index = getVolumeCurves(attr).getVolumeIndexMin();
2830 return NO_ERROR;
2831}
2832
2833status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2834 int &index)
2835{
2836 index = getVolumeCurves(attr).getVolumeIndexMax();
2837 return NO_ERROR;
2838}
2839
Eric Laurent36829f92017-04-07 19:04:42 -07002840audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002841{
2842 // select one output among several suitable for global effects.
2843 // The priority is as follows:
2844 // 1: An offloaded output. If the effect ends up not being offloadable,
2845 // AudioFlinger will invalidate the track and the offloaded output
2846 // will be closed causing the effect to be moved to a PCM output.
2847 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002848 // 3: The primary output
2849 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002850
François Gaffiec005e562018-11-06 15:04:49 +01002851 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2852 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002853 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002854
Eric Laurent36829f92017-04-07 19:04:42 -07002855 if (outputs.size() == 0) {
2856 return AUDIO_IO_HANDLE_NONE;
2857 }
Eric Laurente552edb2014-03-10 17:42:56 -07002858
Eric Laurent36829f92017-04-07 19:04:42 -07002859 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2860 bool activeOnly = true;
2861
2862 while (output == AUDIO_IO_HANDLE_NONE) {
2863 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2864 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2865 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2866
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002867 for (audio_io_handle_t output : outputs) {
2868 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002869 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002870 continue;
2871 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002872 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2873 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002874 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002875 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002876 }
2877 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002878 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002879 }
2880 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002881 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002882 }
2883 }
2884 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2885 output = outputOffloaded;
2886 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2887 output = outputDeepBuffer;
2888 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2889 output = outputPrimary;
2890 } else {
2891 output = outputs[0];
2892 }
2893 activeOnly = false;
2894 }
2895
2896 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002897 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002898 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2899 mMusicEffectOutput = output;
2900 }
2901
2902 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002903 return output;
2904}
2905
Eric Laurent36829f92017-04-07 19:04:42 -07002906audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2907{
2908 return selectOutputForMusicEffects();
2909}
2910
Eric Laurente0720872014-03-11 09:30:41 -07002911status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002912 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002913 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002914 int session,
2915 int id)
2916{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002917 if (session != AUDIO_SESSION_DEVICE) {
2918 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002919 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002920 index = mInputs.indexOfKey(io);
2921 if (index < 0) {
2922 ALOGW("registerEffect() unknown io %d", io);
2923 return INVALID_OPERATION;
2924 }
Eric Laurente552edb2014-03-10 17:42:56 -07002925 }
2926 }
François Gaffiec005e562018-11-06 15:04:49 +01002927 return mEffects.registerEffect(desc, io, session, id,
2928 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2929 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002930}
2931
Eric Laurentc241b0d2018-11-28 09:08:49 -08002932status_t AudioPolicyManager::unregisterEffect(int id)
2933{
2934 if (mEffects.getEffect(id) == nullptr) {
2935 return INVALID_OPERATION;
2936 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002937 if (mEffects.isEffectEnabled(id)) {
2938 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2939 setEffectEnabled(id, false);
2940 }
2941 return mEffects.unregisterEffect(id);
2942}
2943
2944status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2945{
2946 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2947 if (effect == nullptr) {
2948 return INVALID_OPERATION;
2949 }
2950
2951 status_t status = mEffects.setEffectEnabled(id, enabled);
2952 if (status == NO_ERROR) {
2953 mInputs.trackEffectEnabled(effect, enabled);
2954 }
2955 return status;
2956}
2957
Eric Laurent6c796322019-04-09 14:13:17 -07002958
2959status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2960{
2961 mEffects.moveEffects(ids, io);
2962 return NO_ERROR;
2963}
2964
Eric Laurentc75307b2015-03-17 15:29:32 -07002965bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2966{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002967 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002968}
2969
2970bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2971{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002972 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002973}
2974
Eric Laurente0720872014-03-11 09:30:41 -07002975bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002976{
2977 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002978 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002979 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002980 return true;
2981 }
2982 }
2983 return false;
2984}
2985
Eric Laurent275e8e92014-11-30 15:14:47 -08002986// Register a list of custom mixes with their attributes and format.
2987// When a mix is registered, corresponding input and output profiles are
2988// added to the remote submix hw module. The profile contains only the
2989// parameters (sampling rate, format...) specified by the mix.
2990// The corresponding input remote submix device is also connected.
2991//
2992// When a remote submix device is connected, the address is checked to select the
2993// appropriate profile and the corresponding input or output stream is opened.
2994//
2995// When capture starts, getInputForAttr() will:
2996// - 1 look for a mix matching the address passed in attribtutes tags if any
2997// - 2 if none found, getDeviceForInputSource() will:
2998// - 2.1 look for a mix matching the attributes source
2999// - 2.2 if none found, default to device selection by policy rules
3000// At this time, the corresponding output remote submix device is also connected
3001// and active playback use cases can be transferred to this mix if needed when reconnecting
3002// after AudioTracks are invalidated
3003//
3004// When playback starts, getOutputForAttr() will:
3005// - 1 look for a mix matching the address passed in attribtutes tags if any
3006// - 2 if none found, look for a mix matching the attributes usage
3007// - 3 if none found, default to device and output selection by policy rules.
3008
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003009status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003010{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003011 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3012 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003013 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003014 sp<HwModule> rSubmixModule;
3015 // examine each mix's route type
3016 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003017 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003018 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3019 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3020 ALOGE("Unsupported Policy Mix %zu of %zu: "
3021 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3022 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003023 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003024 break;
3025 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003026 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3027 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003028 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003029 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3030 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003031 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003032 rSubmixModule = mHwModules.getModuleFromName(
3033 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3034 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003035 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003036 i);
3037 res = INVALID_OPERATION;
3038 break;
3039 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003040 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003041
Eric Laurent97ac8712018-07-27 18:59:02 -07003042 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003043 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003044 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003045 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003046 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3047 } else {
3048 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3049 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003050 }
François Gaffie036e1e92015-03-19 10:16:24 +01003051
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003052 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003053 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003054 res = INVALID_OPERATION;
3055 break;
3056 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003057 audio_config_t outputConfig = mix.mFormat;
3058 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003059 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3060 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003061 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3062 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003063 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003064 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003065 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003066 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003067
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003068 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3070 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3071 ALOGE("Failed to set remote submix device available, type %u, address %s",
3072 mix.mDeviceType, address.string());
3073 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003074 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003075 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3076 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003077 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003078 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003079 i, mixes.size(), type, address.string());
3080
3081 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3082 mix.mDeviceType, mix.mDeviceAddress,
3083 String8(), AUDIO_FORMAT_DEFAULT);
3084 if (device == nullptr) {
3085 res = INVALID_OPERATION;
3086 break;
3087 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003088
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003089 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003090 // First try to find an already opened output supporting the device
3091 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003092 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003093
Eric Laurentc529cf62020-04-17 18:19:10 -07003094 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003095 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003096 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3097 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003098 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003099 } else {
3100 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003101 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003102 }
3103 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003104 // If no output found, try to find a direct output profile supporting the device
3105 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3106 sp<HwModule> module = mHwModules[i];
3107 for (size_t j = 0;
3108 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3109 j++) {
3110 sp<IOProfile> profile = module->getOutputProfiles()[j];
3111 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3112 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3113 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3114 address.string());
3115 res = INVALID_OPERATION;
3116 } else {
3117 foundOutput = true;
3118 }
3119 }
3120 }
3121 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003122 if (res != NO_ERROR) {
3123 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003124 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003125 res = INVALID_OPERATION;
3126 break;
3127 } else if (!foundOutput) {
3128 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003129 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003130 res = INVALID_OPERATION;
3131 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003132 } else {
3133 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003134 }
Eric Laurentc722f302014-12-10 11:21:49 -08003135 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003136 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003137 if (res != NO_ERROR) {
3138 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003139 } else if (checkOutputs) {
3140 checkForDeviceAndOutputChanges();
3141 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003142 }
3143 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003144}
3145
3146status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3147{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003148 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003149 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003150 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003151 sp<HwModule> rSubmixModule;
3152 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003153 for (const auto& mix : mixes) {
3154 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003155
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003156 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003157 rSubmixModule = mHwModules.getModuleFromName(
3158 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3159 if (rSubmixModule == 0) {
3160 res = INVALID_OPERATION;
3161 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003162 }
3163 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003164
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003165 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003166
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003167 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003168 res = INVALID_OPERATION;
3169 continue;
3170 }
3171
Kevin Rocard04ed0462019-05-02 17:53:24 -07003172 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3173 if (getDeviceConnectionState(device, address.string()) ==
3174 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3175 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3176 address.string(), "remote-submix",
3177 AUDIO_FORMAT_DEFAULT);
3178 if (res != OK) {
3179 ALOGE("Error making RemoteSubmix device unavailable for mix "
3180 "with type %d, address %s", device, address.string());
3181 }
3182 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 }
jiabin5740f082019-08-19 15:08:30 -07003184 rSubmixModule->removeOutputProfile(address.c_str());
3185 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003186
Kevin Rocard153f92d2018-12-18 18:33:28 -08003187 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003188 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003189 res = INVALID_OPERATION;
3190 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003191 } else {
3192 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003193 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003194 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003195 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003196 if (res == NO_ERROR && checkOutputs) {
3197 checkForDeviceAndOutputChanges();
3198 updateCallAndOutputRouting();
3199 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003200 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003201}
3202
Mikhail Naganov100f0122018-11-29 11:22:16 -08003203void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3204{
3205 size_t i = 0;
3206 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3207 for (const auto& fmt : mManualSurroundFormats) {
3208 if (i++ != 0) dst->append(", ");
3209 std::string sfmt;
3210 FormatConverter::toString(fmt, sfmt);
3211 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3212 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3213 }
3214}
3215
Eric Laurentc529cf62020-04-17 18:19:10 -07003216// Returns true if all devices types match the predicate and are supported by one HW module
3217bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003218 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003219 std::function<bool(audio_devices_t)> predicate,
3220 const char *context) {
3221 for (size_t i = 0; i < devices.size(); i++) {
3222 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003223 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003224 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003225 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003226 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003227 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003228 return false;
3229 }
3230 }
3231 return true;
3232}
3233
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003234status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003235 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003236 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003237 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3238 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003239 }
3240 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003241 if (res != NO_ERROR) {
3242 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3243 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003244 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003245
3246 checkForDeviceAndOutputChanges();
3247 updateCallAndOutputRouting();
3248
3249 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003250}
3251
3252status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3253 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003254 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3255 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003256 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003257 __FUNCTION__, uid);
3258 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003259 }
3260
Eric Laurentc529cf62020-04-17 18:19:10 -07003261 checkForDeviceAndOutputChanges();
3262 updateCallAndOutputRouting();
3263
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003264 return res;
3265}
3266
Eric Laurent2517af32020-11-25 15:31:27 +01003267
jiabin0a488932020-08-07 17:32:40 -07003268status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3269 device_role_t role,
3270 const AudioDeviceTypeAddrVector &devices) {
3271 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3272 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003273
Eric Laurentc529cf62020-04-17 18:19:10 -07003274 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003275 return BAD_VALUE;
3276 }
jiabin0a488932020-08-07 17:32:40 -07003277 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003278 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003279 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3280 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003281 return status;
3282 }
3283
3284 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003285
3286 bool forceVolumeReeval = false;
3287 // FIXME: workaround for truncated touch sounds
3288 // to be removed when the problem is handled by system UI
3289 uint32_t delayMs = 0;
3290 if (strategy == mCommunnicationStrategy) {
3291 forceVolumeReeval = true;
3292 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3293 updateInputRouting();
3294 }
3295 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003296
3297 return NO_ERROR;
3298}
3299
3300void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3301{
3302 uint32_t waitMs = 0;
3303 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3304 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3305 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003306 // Only apply special touch sound delay once
3307 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003308 }
3309 for (size_t i = 0; i < mOutputs.size(); i++) {
3310 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3311 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3312 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3313 // As done in setDeviceConnectionState, we could also fix default device issue by
3314 // preventing the force re-routing in case of default dev that distinguishes on address.
3315 // Let's give back to engine full device choice decision however.
3316 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003317 // Only apply special touch sound delay once
3318 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003319 }
3320 if (forceVolumeReeval && !newDevices.isEmpty()) {
3321 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3322 }
3323 }
3324}
3325
Eric Laurent2517af32020-11-25 15:31:27 +01003326void AudioPolicyManager::updateInputRouting() {
3327 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303328 // Skip for hotword recording as the input device switch
3329 // is handled within sound trigger HAL
3330 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3331 continue;
3332 }
Eric Laurent2517af32020-11-25 15:31:27 +01003333 auto newDevice = getNewInputDevice(activeDesc);
3334 // Force new input selection if the new device can not be reached via current input
3335 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3336 setInputDevice(activeDesc->mIoHandle, newDevice);
3337 } else {
3338 closeInput(activeDesc->mIoHandle);
3339 }
3340 }
3341}
3342
jiabin0a488932020-08-07 17:32:40 -07003343status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3344 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003345{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003346 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003347
jiabin0a488932020-08-07 17:32:40 -07003348 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003349 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003350 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3351 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003352 return status;
3353 }
3354
3355 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003356
3357 bool forceVolumeReeval = false;
3358 // FIXME: workaround for truncated touch sounds
3359 // to be removed when the problem is handled by system UI
3360 uint32_t delayMs = 0;
3361 if (strategy == mCommunnicationStrategy) {
3362 forceVolumeReeval = true;
3363 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3364 updateInputRouting();
3365 }
3366 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003367
3368 return NO_ERROR;
3369}
3370
jiabin0a488932020-08-07 17:32:40 -07003371status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3372 device_role_t role,
3373 AudioDeviceTypeAddrVector &devices) {
3374 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003375}
3376
Jiabin Huang3b98d322020-09-03 17:54:16 +00003377status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3378 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3379 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3380 dumpAudioDeviceTypeAddrVector(devices).c_str());
3381
Mikhail Naganov55773032020-10-01 15:08:13 -07003382 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003383 return BAD_VALUE;
3384 }
3385 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3386 ALOGW_IF(status != NO_ERROR,
3387 "Engine could not set preferred devices %s for audio source %d role %d",
3388 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3389
3390 return status;
3391}
3392
3393status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3394 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3395 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3396 dumpAudioDeviceTypeAddrVector(devices).c_str());
3397
Mikhail Naganov55773032020-10-01 15:08:13 -07003398 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003399 return BAD_VALUE;
3400 }
3401 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3402 ALOGW_IF(status != NO_ERROR,
3403 "Engine could not add preferred devices %s for audio source %d role %d",
3404 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3405
Eric Laurent2517af32020-11-25 15:31:27 +01003406 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003407 return status;
3408}
3409
3410status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3411 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3412{
3413 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3414 dumpAudioDeviceTypeAddrVector(devices).c_str());
3415
Mikhail Naganov55773032020-10-01 15:08:13 -07003416 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003417 return BAD_VALUE;
3418 }
3419
3420 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3421 audioSource, role, devices);
3422 ALOGW_IF(status != NO_ERROR,
3423 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3424
Eric Laurent2517af32020-11-25 15:31:27 +01003425 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003426 return status;
3427}
3428
3429status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3430 device_role_t role) {
3431 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3432
3433 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3434 ALOGW_IF(status != NO_ERROR,
3435 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3436
Eric Laurent2517af32020-11-25 15:31:27 +01003437 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003438 return status;
3439}
3440
3441status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3442 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3443 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3444}
3445
Oscar Azucena90e77632019-11-27 17:12:28 -08003446status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003447 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003448 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003449 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3450 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003451 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003452 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3453 if (status != NO_ERROR) {
3454 ALOGE("%s() could not set device affinity for userId %d",
3455 __FUNCTION__, userId);
3456 return status;
3457 }
3458
3459 // reevaluate outputs for all devices
3460 checkForDeviceAndOutputChanges();
3461 updateCallAndOutputRouting();
3462
3463 return NO_ERROR;
3464}
3465
3466status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003467 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003468 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3469 if (status != NO_ERROR) {
3470 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3471 __FUNCTION__, userId);
3472 return status;
3473 }
3474
3475 // reevaluate outputs for all devices
3476 checkForDeviceAndOutputChanges();
3477 updateCallAndOutputRouting();
3478
3479 return NO_ERROR;
3480}
3481
Andy Hungc29d82b2018-10-05 12:23:17 -07003482void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003483{
Andy Hungc29d82b2018-10-05 12:23:17 -07003484 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3485 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003486 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003487 std::string stateLiteral;
3488 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003489 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003490 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3491 "communications", "media", "record", "dock", "system",
3492 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3493 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3494 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003495 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3496 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3497 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3498 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3499 dst->append(" (MANUAL: ");
3500 dumpManualSurroundFormats(dst);
3501 dst->append(")");
3502 }
3503 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003504 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003505 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3506 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003507 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003508 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003509
Andy Hungc29d82b2018-10-05 12:23:17 -07003510 mAvailableOutputDevices.dump(dst, String8("Available output"));
3511 mAvailableInputDevices.dump(dst, String8("Available input"));
3512 mHwModulesAll.dump(dst);
3513 mOutputs.dump(dst);
3514 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003515 mEffects.dump(dst);
3516 mAudioPatches.dump(dst);
3517 mPolicyMixes.dump(dst);
3518 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003519
Kevin Rocardb99cc752019-03-21 20:52:24 -07003520 dst->appendFormat(" AllowedCapturePolicies:\n");
3521 for (auto& policy : mAllowedCapturePolicies) {
3522 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3523 }
3524
François Gaffiec005e562018-11-06 15:04:49 +01003525 dst->appendFormat("\nPolicy Engine dump:\n");
3526 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003527}
3528
3529status_t AudioPolicyManager::dump(int fd)
3530{
3531 String8 result;
3532 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003533 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003534 return NO_ERROR;
3535}
3536
Kevin Rocardb99cc752019-03-21 20:52:24 -07003537status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3538{
3539 mAllowedCapturePolicies[uid] = capturePolicy;
3540 return NO_ERROR;
3541}
3542
Eric Laurente552edb2014-03-10 17:42:56 -07003543// This function checks for the parameters which can be offloaded.
3544// This can be enhanced depending on the capability of the DSP and policy
3545// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003546audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003547{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003548 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003549 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003550 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003551 offloadInfo.format,
3552 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3553 offloadInfo.has_video);
3554
Andy Hung2ddee192015-12-18 17:34:44 -08003555 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003556 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003557 }
3558
Eric Laurente552edb2014-03-10 17:42:56 -07003559 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003560 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003561 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3562 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003563 }
3564
3565 // Check if stream type is music, then only allow offload as of now.
3566 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3567 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003568 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3569 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003570 }
3571
3572 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003573 const bool allowOffloadWithVideo =
3574 property_get_bool("audio.offload.video", false /* default_value */);
3575 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003576 ALOGV("%s: has_video == true, returning false", __func__);
3577 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003578 }
3579
3580 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003581 const int min_duration_secs = property_get_int32(
3582 "audio.offload.min.duration.secs", -1 /* default_value */);
3583 if (min_duration_secs >= 0) {
3584 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003585 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3586 __func__, min_duration_secs);
3587 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003588 }
3589 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003590 ALOGV("%s: Offload denied by duration < default min(=%u)",
3591 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3592 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003593 }
3594
3595 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3596 // creating an offloaded track and tearing it down immediately after start when audioflinger
3597 // detects there is an active non offloadable effect.
3598 // FIXME: We should check the audio session here but we do not have it in this context.
3599 // This may prevent offloading in rare situations where effects are left active by apps
3600 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003601 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003602 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003603 }
3604
3605 // See if there is a profile to support this.
3606 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003607 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003608 offloadInfo.sample_rate,
3609 offloadInfo.format,
3610 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003611 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3612 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003613 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3614 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3615 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003616 if (profile == nullptr) {
3617 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3618 }
3619 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3620 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3621 }
3622 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003623}
3624
Michael Chana94fbb22018-04-24 14:31:19 +10003625bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3626 const audio_attributes_t& attributes) {
3627 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003628 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003629 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003630 config.sample_rate,
3631 config.format,
3632 config.channel_mask,
3633 output_flags,
3634 true /* directOnly */);
3635 ALOGV("%s() profile %sfound with name: %s, "
3636 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3637 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003638 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003639 config.sample_rate, config.format, config.channel_mask, output_flags);
3640 return (profile != 0);
3641}
3642
Eric Laurent6a94d692014-05-20 11:18:06 -07003643status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3644 audio_port_type_t type,
3645 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003646 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003647 unsigned int *generation)
3648{
jiabin19cdba52020-11-24 11:28:58 -08003649 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3650 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003651 return BAD_VALUE;
3652 }
3653 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003654 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003655 *num_ports = 0;
3656 }
3657
3658 size_t portsWritten = 0;
3659 size_t portsMax = *num_ports;
3660 *num_ports = 0;
3661 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003662 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3663 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003664 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003665 for (const auto& dev : mAvailableOutputDevices) {
3666 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003667 continue;
3668 }
3669 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003670 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003671 }
3672 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003673 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003674 }
3675 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003676 for (const auto& dev : mAvailableInputDevices) {
3677 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003678 continue;
3679 }
3680 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003681 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003682 }
3683 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003684 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003685 }
3686 }
3687 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3688 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3689 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3690 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3691 }
3692 *num_ports += mInputs.size();
3693 }
3694 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003695 size_t numOutputs = 0;
3696 for (size_t i = 0; i < mOutputs.size(); i++) {
3697 if (!mOutputs[i]->isDuplicated()) {
3698 numOutputs++;
3699 if (portsWritten < portsMax) {
3700 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3701 }
3702 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003703 }
Eric Laurent84c70242014-06-23 08:46:27 -07003704 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 }
3706 }
3707 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003708 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 return NO_ERROR;
3710}
3711
jiabin19cdba52020-11-24 11:28:58 -08003712status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003713{
Eric Laurent99fcae42018-05-17 16:59:18 -07003714 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3715 return BAD_VALUE;
3716 }
3717 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3718 if (dev != 0) {
3719 dev->toAudioPort(port);
3720 return NO_ERROR;
3721 }
3722 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3723 if (dev != 0) {
3724 dev->toAudioPort(port);
3725 return NO_ERROR;
3726 }
3727 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3728 if (out != 0) {
3729 out->toAudioPort(port);
3730 return NO_ERROR;
3731 }
3732 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3733 if (in != 0) {
3734 in->toAudioPort(port);
3735 return NO_ERROR;
3736 }
3737 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003738}
3739
François Gaffieafd4cea2019-11-18 15:50:22 +01003740status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3741 audio_patch_handle_t *handle,
3742 uid_t uid, uint32_t delayMs,
3743 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003744{
François Gaffieafd4cea2019-11-18 15:50:22 +01003745 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003746 if (handle == NULL || patch == NULL) {
3747 return BAD_VALUE;
3748 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003749 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003750
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003751 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003752 return BAD_VALUE;
3753 }
3754 // only one source per audio patch supported for now
3755 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003756 return INVALID_OPERATION;
3757 }
Eric Laurent874c42872014-08-08 15:13:39 -07003758
3759 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003760 return INVALID_OPERATION;
3761 }
Eric Laurent874c42872014-08-08 15:13:39 -07003762 for (size_t i = 0; i < patch->num_sinks; i++) {
3763 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3764 return INVALID_OPERATION;
3765 }
3766 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003767
3768 sp<AudioPatch> patchDesc;
3769 ssize_t index = mAudioPatches.indexOfKey(*handle);
3770
François Gaffieafd4cea2019-11-18 15:50:22 +01003771 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3772 patch->sources[0].role,
3773 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003774#if LOG_NDEBUG == 0
3775 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003776 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3777 patch->sinks[i].role,
3778 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003779 }
3780#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003781
3782 if (index >= 0) {
3783 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003784 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3785 __func__, mUidCached, patchDesc->getUid(), uid);
3786 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003787 return INVALID_OPERATION;
3788 }
3789 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003790 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003791 }
3792
3793 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003794 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003795 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003796 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003797 return BAD_VALUE;
3798 }
Eric Laurent84c70242014-06-23 08:46:27 -07003799 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3800 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003801 if (patchDesc != 0) {
3802 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003803 ALOGV("%s source id differs for patch current id %d new id %d",
3804 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003805 return BAD_VALUE;
3806 }
3807 }
Eric Laurent874c42872014-08-08 15:13:39 -07003808 DeviceVector devices;
3809 for (size_t i = 0; i < patch->num_sinks; i++) {
3810 // Only support mix to devices connection
3811 // TODO add support for mix to mix connection
3812 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003813 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003814 return INVALID_OPERATION;
3815 }
3816 sp<DeviceDescriptor> devDesc =
3817 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3818 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003819 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003820 return BAD_VALUE;
3821 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003822
François Gaffie11d30102018-11-02 16:09:09 +01003823 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003824 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003825 NULL, // updatedSamplingRate
3826 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003827 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003828 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003829 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003830 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003831 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003832 return INVALID_OPERATION;
3833 }
3834 devices.add(devDesc);
3835 }
3836 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003837 return INVALID_OPERATION;
3838 }
Eric Laurent874c42872014-08-08 15:13:39 -07003839
Eric Laurent6a94d692014-05-20 11:18:06 -07003840 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003841 ALOGV("%s setting device %s on output %d",
3842 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003843 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003844 index = mAudioPatches.indexOfKey(*handle);
3845 if (index >= 0) {
3846 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003847 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 }
3849 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 patchDesc->setUid(uid);
3851 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003853 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003854 return INVALID_OPERATION;
3855 }
3856 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3857 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3858 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003859 // only one sink supported when connecting an input device to a mix
3860 if (patch->num_sinks > 1) {
3861 return INVALID_OPERATION;
3862 }
François Gaffie53615e22015-03-19 09:24:12 +01003863 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 if (inputDesc == NULL) {
3865 return BAD_VALUE;
3866 }
3867 if (patchDesc != 0) {
3868 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3869 return BAD_VALUE;
3870 }
3871 }
François Gaffie11d30102018-11-02 16:09:09 +01003872 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003873 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003874 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003875 return BAD_VALUE;
3876 }
3877
François Gaffie11d30102018-11-02 16:09:09 +01003878 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003879 patch->sinks[0].sample_rate,
3880 NULL, /*updatedSampleRate*/
3881 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003882 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003883 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003884 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003885 // FIXME for the parameter type,
3886 // and the NONE
3887 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003888 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 return INVALID_OPERATION;
3890 }
3891 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003892 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003893 device->toString().c_str(), inputDesc->mIoHandle);
3894 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 index = mAudioPatches.indexOfKey(*handle);
3896 if (index >= 0) {
3897 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003898 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003899 }
3900 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003901 patchDesc->setUid(uid);
3902 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003903 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003904 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003905 return INVALID_OPERATION;
3906 }
3907 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3908 // device to device connection
3909 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003910 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003911 return BAD_VALUE;
3912 }
3913 }
François Gaffie11d30102018-11-02 16:09:09 +01003914 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003916 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003917 return BAD_VALUE;
3918 }
Eric Laurent874c42872014-08-08 15:13:39 -07003919
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 //update source and sink with our own data as the data passed in the patch may
3921 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003922 PatchBuilder patchBuilder;
3923 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003924
3925 // if first sink is to MSD, establish single MSD patch
3926 if (getMsdAudioOutDevices().contains(
3927 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3928 ALOGV("%s patching to MSD", __FUNCTION__);
3929 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3930 goto installPatch;
3931 }
3932
François Gaffieafd4cea2019-11-18 15:50:22 +01003933 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3934 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003935
Eric Laurent874c42872014-08-08 15:13:39 -07003936 for (size_t i = 0; i < patch->num_sinks; i++) {
3937 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003938 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003939 return INVALID_OPERATION;
3940 }
François Gaffie11d30102018-11-02 16:09:09 +01003941 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003942 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003943 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003944 return BAD_VALUE;
3945 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003946 audio_port_config sinkPortConfig = {};
3947 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3948 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003949
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003950 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3951 // volume management purpose (tracking activity)
3952 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
3953 // in config XML to reach the sink so that is can be declared as available.
3954 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3955 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
3956 if (sourceDesc != nullptr) {
3957 // take care of dynamic routing for SwOutput selection,
3958 audio_attributes_t attributes = sourceDesc->attributes();
3959 audio_stream_type_t stream = sourceDesc->stream();
3960 audio_attributes_t resultAttr;
3961 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3962 config.sample_rate = sourceDesc->config().sample_rate;
3963 config.channel_mask = sourceDesc->config().channel_mask;
3964 config.format = sourceDesc->config().format;
3965 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3966 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3967 bool isRequestedDeviceForExclusiveUse = false;
3968 output_type_t outputType;
3969 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3970 &stream, sourceDesc->uid(), &config, &flags,
3971 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3972 nullptr, &outputType);
3973 if (output == AUDIO_IO_HANDLE_NONE) {
3974 ALOGV("%s no output for device %s",
3975 __FUNCTION__, sinkDevice->toString().c_str());
3976 return INVALID_OPERATION;
3977 }
3978 outputDesc = mOutputs.valueFor(output);
3979 if (outputDesc->isDuplicated()) {
3980 ALOGE("%s output is duplicated", __func__);
3981 return INVALID_OPERATION;
3982 }
3983 sourceDesc->setSwOutput(outputDesc);
3984 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07003985 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003986 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003987 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003988 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003989 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3990 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003991 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3992 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003993 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3994 (sourceDesc != nullptr &&
3995 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003996 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003997 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003998 return INVALID_OPERATION;
3999 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004000 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004001 SortedVector<audio_io_handle_t> outputs =
4002 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4003 // if the sink device is reachable via an opened output stream, request to
4004 // go via this output stream by adding a second source to the patch
4005 // description
4006 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004007 if (output != AUDIO_IO_HANDLE_NONE) {
4008 outputDesc = mOutputs.valueFor(output);
4009 if (outputDesc->isDuplicated()) {
4010 ALOGV("%s output for device %s is duplicated",
4011 __FUNCTION__, sinkDevice->toString().c_str());
4012 return INVALID_OPERATION;
4013 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004014 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004015 }
4016 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004017 audio_port_config srcMixPortConfig = {};
4018 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004019 // for volume control, we may need a valid stream
4020 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4021 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4022 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004023 }
Eric Laurent83b88082014-06-20 18:31:16 -07004024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 }
4026 // TODO: check from routing capabilities in config file and other conflicting patches
4027
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004028installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004029 status_t status = installPatch(
4030 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004031 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004032 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004033 return INVALID_OPERATION;
4034 }
4035 } else {
4036 return BAD_VALUE;
4037 }
4038 } else {
4039 return BAD_VALUE;
4040 }
4041 return NO_ERROR;
4042}
4043
4044status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4045 uid_t uid)
4046{
4047 ALOGV("releaseAudioPatch() patch %d", handle);
4048
4049 ssize_t index = mAudioPatches.indexOfKey(handle);
4050
4051 if (index < 0) {
4052 return BAD_VALUE;
4053 }
4054 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004055 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4056 __func__, mUidCached, patchDesc->getUid(), uid);
4057 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004058 return INVALID_OPERATION;
4059 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004060 return releaseAudioPatchInternal(handle);
4061}
Eric Laurent6a94d692014-05-20 11:18:06 -07004062
François Gaffieafd4cea2019-11-18 15:50:22 +01004063status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4064 uint32_t delayMs)
4065{
4066 ALOGV("%s patch %d", __func__, handle);
4067 if (mAudioPatches.indexOfKey(handle) < 0) {
4068 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4069 return BAD_VALUE;
4070 }
4071 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004072 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004073 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004074 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004075 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004076 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004077 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004078 return BAD_VALUE;
4079 }
4080
François Gaffie11d30102018-11-02 16:09:09 +01004081 setOutputDevices(outputDesc,
4082 getNewOutputDevices(outputDesc, true /*fromCache*/),
4083 true,
4084 0,
4085 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004086 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4087 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004088 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004089 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004090 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 return BAD_VALUE;
4092 }
4093 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004094 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004095 true,
4096 NULL);
4097 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004098 status_t status =
4099 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4100 ALOGV("%s patch panel returned %d patchHandle %d",
4101 __func__, status, patchDesc->getAfHandle());
4102 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004103 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004104 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004105 // SW Bridge
4106 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4107 sp<SwAudioOutputDescriptor> outputDesc =
4108 mOutputs.getOutputFromId(patch->sources[1].id);
4109 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004110 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4111 // releaseOutput has already called closeOuput in case of direct output
4112 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004113 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004114 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4115 // force SwOutput patch removal as AF counter part patch has already gone.
4116 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4117 removeAudioPatch(outputDesc->getPatchHandle());
4118 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004119 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4120 setOutputDevices(outputDesc,
4121 getNewOutputDevices(outputDesc, true /*fromCache*/),
4122 true, /*force*/
4123 0,
4124 NULL);
4125 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004126 } else {
4127 return BAD_VALUE;
4128 }
4129 } else {
4130 return BAD_VALUE;
4131 }
4132 return NO_ERROR;
4133}
4134
4135status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4136 struct audio_patch *patches,
4137 unsigned int *generation)
4138{
François Gaffie53615e22015-03-19 09:24:12 +01004139 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004140 return BAD_VALUE;
4141 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004143 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004144}
4145
Eric Laurente1715a42014-05-20 11:30:42 -07004146status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004147{
Eric Laurente1715a42014-05-20 11:30:42 -07004148 ALOGV("setAudioPortConfig()");
4149
4150 if (config == NULL) {
4151 return BAD_VALUE;
4152 }
4153 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4154 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004155 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4156 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004157 }
4158
Eric Laurenta121f902014-06-03 13:32:54 -07004159 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004160 if (config->type == AUDIO_PORT_TYPE_MIX) {
4161 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004162 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004163 if (outputDesc == NULL) {
4164 return BAD_VALUE;
4165 }
Eric Laurent84c70242014-06-23 08:46:27 -07004166 ALOG_ASSERT(!outputDesc->isDuplicated(),
4167 "setAudioPortConfig() called on duplicated output %d",
4168 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004169 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004170 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004171 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004172 if (inputDesc == NULL) {
4173 return BAD_VALUE;
4174 }
Eric Laurenta121f902014-06-03 13:32:54 -07004175 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004176 } else {
4177 return BAD_VALUE;
4178 }
4179 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4180 sp<DeviceDescriptor> deviceDesc;
4181 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4182 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4183 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4184 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4185 } else {
4186 return BAD_VALUE;
4187 }
4188 if (deviceDesc == NULL) {
4189 return BAD_VALUE;
4190 }
Eric Laurenta121f902014-06-03 13:32:54 -07004191 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004192 } else {
4193 return BAD_VALUE;
4194 }
4195
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004196 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004197 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4198 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004199 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004200 audioPortConfig->toAudioPortConfig(&newConfig, config);
4201 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004202 }
Eric Laurenta121f902014-06-03 13:32:54 -07004203 if (status != NO_ERROR) {
4204 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004205 }
Eric Laurente1715a42014-05-20 11:30:42 -07004206
4207 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004208}
4209
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004210void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4211{
Eric Laurentd60560a2015-04-10 11:31:20 -07004212 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004213 clearAudioPatches(uid);
4214 clearSessionRoutes(uid);
4215}
4216
Eric Laurent6a94d692014-05-20 11:18:06 -07004217void AudioPolicyManager::clearAudioPatches(uid_t uid)
4218{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004219 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004221 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004222 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004223 }
4224 }
4225}
4226
François Gaffiec005e562018-11-06 15:04:49 +01004227void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004228{
François Gaffiec005e562018-11-06 15:04:49 +01004229 // Take the first attributes following the product strategy as it is used to retrieve the routed
4230 // device. All attributes wihin a strategy follows the same "routing strategy"
4231 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4232 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004233 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004234 for (size_t j = 0; j < mOutputs.size(); j++) {
4235 if (mOutputs.keyAt(j) == ouptutToSkip) {
4236 continue;
4237 }
4238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004239 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004240 continue;
4241 }
4242 // If the default device for this strategy is on another output mix,
4243 // invalidate all tracks in this strategy to force re connection.
4244 // Otherwise select new device on the output mix.
4245 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004246 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4247 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004248 }
4249 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004250 setOutputDevices(
4251 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004252 }
4253 }
4254}
4255
4256void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4257{
4258 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004259 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004260 for (size_t i = 0; i < mOutputs.size(); i++) {
4261 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004262 for (const auto& client : outputDesc->getClientIterable()) {
4263 if (client->hasPreferredDevice() && client->uid() == uid) {
4264 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004265 auto clientStrategy = client->strategy();
4266 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4267 end(affectedStrategies)) {
4268 continue;
4269 }
4270 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004271 }
4272 }
4273 }
4274 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004275 for (const auto& strategy : affectedStrategies) {
4276 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004277 }
4278
4279 // remove input routes associated with this uid
4280 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004281 for (size_t i = 0; i < mInputs.size(); i++) {
4282 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004283 for (const auto& client : inputDesc->getClientIterable()) {
4284 if (client->hasPreferredDevice() && client->uid() == uid) {
4285 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4286 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004287 }
4288 }
4289 }
4290 // reroute inputs if necessary
4291 SortedVector<audio_io_handle_t> inputsToClose;
4292 for (size_t i = 0; i < mInputs.size(); i++) {
4293 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004294 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004295 inputsToClose.add(inputDesc->mIoHandle);
4296 }
4297 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004298 for (const auto& input : inputsToClose) {
4299 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004300 }
4301}
4302
Eric Laurentd60560a2015-04-10 11:31:20 -07004303void AudioPolicyManager::clearAudioSources(uid_t uid)
4304{
4305 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004306 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4307 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004308 stopAudioSource(mAudioSources.keyAt(i));
4309 }
4310 }
4311}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004312
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004313status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4314 audio_io_handle_t *ioHandle,
4315 audio_devices_t *device)
4316{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004317 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4318 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004319 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004320 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004321
François Gaffiedf372692015-03-19 10:43:27 +01004322 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004323}
4324
Eric Laurentd60560a2015-04-10 11:31:20 -07004325status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004326 const audio_attributes_t *attributes,
4327 audio_port_handle_t *portId,
4328 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004329{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004330 ALOGV("%s", __FUNCTION__);
4331 *portId = AUDIO_PORT_HANDLE_NONE;
4332
4333 if (source == NULL || attributes == NULL || portId == NULL) {
4334 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4335 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004336 return BAD_VALUE;
4337 }
4338
Eric Laurentd60560a2015-04-10 11:31:20 -07004339 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4340 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004341 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4342 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004343 return INVALID_OPERATION;
4344 }
4345
François Gaffie11d30102018-11-02 16:09:09 +01004346 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004347 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004348 String8(source->ext.device.address),
4349 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004350 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004351 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004352 return BAD_VALUE;
4353 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004354
jiabin4ef93452019-09-10 14:29:54 -07004355 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004356
François Gaffieaaac0fd2018-11-22 17:56:39 +01004357 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004358 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004359 mEngine->getStreamTypeForAttributes(*attributes),
4360 mEngine->getProductStrategyForAttributes(*attributes),
4361 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004362
4363 status_t status = connectAudioSource(sourceDesc);
4364 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004365 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004366 }
4367 return status;
4368}
4369
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004370status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004371{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004372 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004373
4374 // make sure we only have one patch per source.
4375 disconnectAudioSource(sourceDesc);
4376
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004377 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004378 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4379 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4380 sourceDesc->srcDevice()->type(),
4381 String8(sourceDesc->srcDevice()->address().c_str()),
4382 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004383 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004384 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004385 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004386 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004387 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4388 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4389 return INVALID_OPERATION;
4390 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004391 PatchBuilder patchBuilder;
4392 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4393 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4394 status_t status =
4395 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4396 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4397 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4398 return INVALID_OPERATION;
4399 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004400 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004401 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4402 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4403 if (swOutput != 0) {
4404 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004405 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004406 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004407 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004408 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004409 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004410 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004411 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004412 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004413 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004414 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004415 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4417 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004418 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004419 if (delayMs != 0) {
4420 usleep(delayMs * 1000);
4421 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004422 } else {
4423 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4424 if (hwOutputDesc != 0) {
4425 // create Hwoutput and add to mHwOutputs
4426 } else {
4427 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4428 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004429 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004430 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004431
4432FailureSourceActive:
4433 swOutput->stop();
4434 releaseOutput(sourceDesc->portId());
4435FailureSourceAdded:
4436 sourceDesc->setSwOutput(nullptr);
4437FailureReleasePatch:
4438 releaseAudioPatchInternal(handle);
4439 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004440}
4441
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004442status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004443{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004444 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4445 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004446 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004447 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004448 return BAD_VALUE;
4449 }
4450 status_t status = disconnectAudioSource(sourceDesc);
4451
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004452 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004453 return status;
4454}
4455
Andy Hung2ddee192015-12-18 17:34:44 -08004456status_t AudioPolicyManager::setMasterMono(bool mono)
4457{
4458 if (mMasterMono == mono) {
4459 return NO_ERROR;
4460 }
4461 mMasterMono = mono;
4462 // if enabling mono we close all offloaded devices, which will invalidate the
4463 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4464 // for recreating the new AudioTrack as non-offloaded PCM.
4465 //
4466 // If disabling mono, we leave all tracks as is: we don't know which clients
4467 // and tracks are able to be recreated as offloaded. The next "song" should
4468 // play back offloaded.
4469 if (mMasterMono) {
4470 Vector<audio_io_handle_t> offloaded;
4471 for (size_t i = 0; i < mOutputs.size(); ++i) {
4472 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4473 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4474 offloaded.push(desc->mIoHandle);
4475 }
4476 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004477 for (const auto& handle : offloaded) {
4478 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004479 }
4480 }
4481 // update master mono for all remaining outputs
4482 for (size_t i = 0; i < mOutputs.size(); ++i) {
4483 updateMono(mOutputs.keyAt(i));
4484 }
4485 return NO_ERROR;
4486}
4487
4488status_t AudioPolicyManager::getMasterMono(bool *mono)
4489{
4490 *mono = mMasterMono;
4491 return NO_ERROR;
4492}
4493
Eric Laurentac9cef52017-06-09 15:46:26 -07004494float AudioPolicyManager::getStreamVolumeDB(
4495 audio_stream_type_t stream, int index, audio_devices_t device)
4496{
jiabin9a3361e2019-10-01 09:38:30 -07004497 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004498}
4499
jiabin81772902018-04-02 17:52:27 -07004500status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4501 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004502 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004503{
Kriti Dang6537def2021-03-02 13:46:59 +01004504 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4505 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004506 return BAD_VALUE;
4507 }
Kriti Dang6537def2021-03-02 13:46:59 +01004508 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4509 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004510
4511 size_t formatsWritten = 0;
4512 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004513
Kriti Dang6537def2021-03-02 13:46:59 +01004514 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004515 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4516 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004517 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004518 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004519 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004520 bool formatEnabled = true;
4521 switch (forceUse) {
4522 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004523 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004524 break;
4525 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4526 formatEnabled = false;
4527 break;
4528 default: // AUTO or ALWAYS => true
4529 break;
jiabin81772902018-04-02 17:52:27 -07004530 }
4531 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4532 }
jiabin81772902018-04-02 17:52:27 -07004533 }
4534 return NO_ERROR;
4535}
4536
Kriti Dang6537def2021-03-02 13:46:59 +01004537status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4538 audio_format_t *surroundFormats) {
4539 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4540 return BAD_VALUE;
4541 }
4542 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4543 __func__, *numSurroundFormats, surroundFormats);
4544
4545 size_t formatsWritten = 0;
4546 size_t formatsMax = *numSurroundFormats;
4547 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4548
4549 // Return formats from all device profiles that have already been resolved by
4550 // checkOutputsForDevice().
4551 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4552 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4553 audio_devices_t deviceType = device->type();
4554 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4555 // returns formats reported by HDMI devices.
4556 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4557 continue;
4558 }
4559 // Formats reported by sink devices
4560 std::unordered_set<audio_format_t> formatset;
4561 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4562 formatset.insert(it->second.begin(), it->second.end());
4563 }
4564
4565 // Formats hard-coded in the in policy configuration file (if any).
4566 FormatVector encodedFormats = device->encodedFormats();
4567 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4568 // Filter the formats which are supported by the vendor hardware.
4569 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4570 if (mConfig.getSurroundFormats().count(*it) != 0) {
4571 formats.insert(*it);
4572 } else {
4573 for (const auto& pair : mConfig.getSurroundFormats()) {
4574 if (pair.second.count(*it) != 0) {
4575 formats.insert(pair.first);
4576 break;
4577 }
4578 }
4579 }
4580 }
4581 }
4582 *numSurroundFormats = formats.size();
4583 for (const auto& format: formats) {
4584 if (formatsWritten < formatsMax) {
4585 surroundFormats[formatsWritten++] = format;
4586 }
4587 }
4588 return NO_ERROR;
4589}
4590
jiabin81772902018-04-02 17:52:27 -07004591status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4592{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004593 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004594 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4595 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004596 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004597 return BAD_VALUE;
4598 }
4599
Mikhail Naganov100f0122018-11-29 11:22:16 -08004600 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4601 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004602 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004603 return INVALID_OPERATION;
4604 }
4605
Mikhail Naganov100f0122018-11-29 11:22:16 -08004606 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004607 return NO_ERROR;
4608 }
4609
Mikhail Naganov100f0122018-11-29 11:22:16 -08004610 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004611 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004612 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004613 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004614 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004615 }
4616 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004617 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004618 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004619 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004620 }
4621 }
4622
4623 sp<SwAudioOutputDescriptor> outputDesc;
4624 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004625 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4626 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004627 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4628 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004629 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004630 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004631 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4632 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4633 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004634 name.c_str(),
4635 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004636 if (status != NO_ERROR) {
4637 continue;
4638 }
4639 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4640 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4641 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004642 name.c_str(),
4643 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004644 profileUpdated |= (status == NO_ERROR);
4645 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004646 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004647 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004648 AUDIO_DEVICE_IN_HDMI);
4649 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4650 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004651 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004652 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004653 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4654 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4655 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004656 name.c_str(),
4657 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004658 if (status != NO_ERROR) {
4659 continue;
4660 }
4661 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4662 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4663 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004664 name.c_str(),
4665 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004666 profileUpdated |= (status == NO_ERROR);
4667 }
4668
jiabin81772902018-04-02 17:52:27 -07004669 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004670 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004671 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004672 }
4673
4674 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4675}
4676
Eric Laurent5ada82e2019-08-29 17:53:54 -07004677void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004678{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004679 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004680 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004681 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004682 }
4683}
4684
jiabin6012f912018-11-02 17:06:30 -07004685bool AudioPolicyManager::isHapticPlaybackSupported()
4686{
4687 for (const auto& hwModule : mHwModules) {
4688 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4689 for (const auto &outProfile : outputProfiles) {
4690 struct audio_port audioPort;
4691 outProfile->toAudioPort(&audioPort);
4692 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4693 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4694 return true;
4695 }
4696 }
4697 }
4698 }
4699 return false;
4700}
4701
Eric Laurent8340e672019-11-06 11:01:08 -08004702bool AudioPolicyManager::isCallScreenModeSupported()
4703{
4704 return getConfig().isCallScreenModeSupported();
4705}
4706
4707
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004708status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004709{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004710 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004711 if (!sourceDesc->isConnected()) {
4712 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4713 return NO_ERROR;
4714 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004715 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4716 if (swOutput != 0) {
4717 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004718 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004719 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004720 }
jiabinbce0c1d2020-10-05 11:20:18 -07004721 if (releaseOutput(sourceDesc->portId())) {
4722 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4723 // no need to release audio patch here but just return NO_ERROR.
4724 return NO_ERROR;
4725 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004726 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004727 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004728 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004729 // close Hwoutput and remove from mHwOutputs
4730 } else {
4731 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4732 }
4733 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004734 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4735 sourceDesc->disconnect();
4736 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004737}
4738
François Gaffiec005e562018-11-06 15:04:49 +01004739sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4740 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004741{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004742 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004743 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004744 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004745 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004746 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4747 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004748 source = sourceDesc;
4749 break;
4750 }
4751 }
4752 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004753}
4754
Eric Laurente552edb2014-03-10 17:42:56 -07004755// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004756// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004757// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004758uint32_t AudioPolicyManager::nextAudioPortGeneration()
4759{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004760 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004761}
4762
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004763static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004764 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4765 !audioPolicyXmlConfigFile.empty()) {
4766 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4767 if (ret == NO_ERROR) {
4768 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004769 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004770 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004771 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004772 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004773}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004774
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004775AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4776 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004777 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004778 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004779 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004780 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004781 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004782 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004783 mAudioPortGeneration(1),
4784 mBeaconMuteRefCount(0),
4785 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004786 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004787 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004788 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004789 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004790{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004791}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004792
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004793AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4794 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4795{
4796 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004797}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004798
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004799void AudioPolicyManager::loadConfig() {
4800 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004801 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004802 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004803 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004804}
4805
4806status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004807 {
4808 auto engLib = EngineLibrary::load(
4809 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4810 if (!engLib) {
4811 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4812 return NO_INIT;
4813 }
4814 mEngine = engLib->createEngine();
4815 if (mEngine == nullptr) {
4816 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4817 return NO_INIT;
4818 }
François Gaffie2110e042015-03-24 08:41:51 +01004819 }
4820 mEngine->setObserver(this);
4821 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004822 if (status != NO_ERROR) {
4823 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4824 return status;
4825 }
François Gaffie2110e042015-03-24 08:41:51 +01004826
Eric Laurent1d69c872021-01-11 18:53:01 +01004827 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4828 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4829
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004830 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004831 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004832 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004833
Eric Laurent3a4311c2014-03-17 12:00:47 -07004834 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004835 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4836 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4837 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004838 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004839 }
jiabin9ff780e2018-03-19 18:19:52 -07004840 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004841 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004842 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004843 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004844 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004845 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004846 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004847 }
4848 }
4849 }
Eric Laurente552edb2014-03-10 17:42:56 -07004850
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004851 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004852
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004853 // Silence ALOGV statements
4854 property_set("log.tag." LOG_TAG, "D");
4855
Eric Laurente552edb2014-03-10 17:42:56 -07004856 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004857 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004858}
4859
Eric Laurente0720872014-03-11 09:30:41 -07004860AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004861{
Eric Laurente552edb2014-03-10 17:42:56 -07004862 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004863 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004864 }
4865 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004866 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004867 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004868 mAvailableOutputDevices.clear();
4869 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004870 mOutputs.clear();
4871 mInputs.clear();
4872 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004873 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004874 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004875}
4876
Eric Laurente0720872014-03-11 09:30:41 -07004877status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004878{
Eric Laurent87ffa392015-05-22 10:32:38 -07004879 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004880}
4881
Eric Laurente552edb2014-03-10 17:42:56 -07004882// ---
4883
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004884void AudioPolicyManager::onNewAudioModulesAvailable()
4885{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004886 DeviceVector newDevices;
4887 onNewAudioModulesAvailableInt(&newDevices);
4888 if (!newDevices.empty()) {
4889 nextAudioPortGeneration();
4890 mpClientInterface->onAudioPortListUpdate();
4891 }
4892}
4893
4894void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4895{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004896 for (const auto& hwModule : mHwModulesAll) {
4897 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4898 continue;
4899 }
4900 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4901 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4902 ALOGW("could not open HW module %s", hwModule->getName());
4903 continue;
4904 }
4905 mHwModules.push_back(hwModule);
4906 // open all output streams needed to access attached devices
4907 // except for direct output streams that are only opened when they are actually
4908 // required by an app.
4909 // This also validates mAvailableOutputDevices list
4910 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4911 if (!outProfile->canOpenNewIo()) {
4912 ALOGE("Invalid Output profile max open count %u for profile %s",
4913 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4914 continue;
4915 }
4916 if (!outProfile->hasSupportedDevices()) {
4917 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4918 continue;
4919 }
4920 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4921 mTtsOutputAvailable = true;
4922 }
4923
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004924 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4925 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4926 sp<DeviceDescriptor> supportedDevice = 0;
4927 if (supportedDevices.contains(mDefaultOutputDevice)) {
4928 supportedDevice = mDefaultOutputDevice;
4929 } else {
4930 // choose first device present in profile's SupportedDevices also part of
4931 // mAvailableOutputDevices.
4932 if (availProfileDevices.isEmpty()) {
4933 continue;
4934 }
4935 supportedDevice = availProfileDevices.itemAt(0);
4936 }
4937 if (!mOutputDevicesAll.contains(supportedDevice)) {
4938 continue;
4939 }
4940 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4941 mpClientInterface);
4942 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4943 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4944 AUDIO_STREAM_DEFAULT,
4945 AUDIO_OUTPUT_FLAG_NONE, &output);
4946 if (status != NO_ERROR) {
4947 ALOGW("Cannot open output stream for devices %s on hw module %s",
4948 supportedDevice->toString().c_str(), hwModule->getName());
4949 continue;
4950 }
4951 for (const auto &device : availProfileDevices) {
4952 // give a valid ID to an attached device once confirmed it is reachable
4953 if (!device->isAttached()) {
4954 device->attach(hwModule);
4955 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004956 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004957 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004958 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4959 }
4960 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004961 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004962 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4963 mPrimaryOutput = outputDesc;
4964 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004965 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4966 outputDesc->close();
4967 } else {
4968 addOutput(output, outputDesc);
4969 setOutputDevices(outputDesc,
4970 DeviceVector(supportedDevice),
4971 true,
4972 0,
4973 NULL);
4974 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004975 }
4976 // open input streams needed to access attached devices to validate
4977 // mAvailableInputDevices list
4978 for (const auto& inProfile : hwModule->getInputProfiles()) {
4979 if (!inProfile->canOpenNewIo()) {
4980 ALOGE("Invalid Input profile max open count %u for profile %s",
4981 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4982 continue;
4983 }
4984 if (!inProfile->hasSupportedDevices()) {
4985 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4986 continue;
4987 }
4988 // chose first device present in profile's SupportedDevices also part of
4989 // available input devices
4990 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4991 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4992 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004993 ALOGV("%s: Input device list is empty! for profile %s",
4994 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004995 continue;
4996 }
4997 sp<AudioInputDescriptor> inputDesc =
4998 new AudioInputDescriptor(inProfile, mpClientInterface);
4999
5000 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5001 status_t status = inputDesc->open(nullptr,
5002 availProfileDevices.itemAt(0),
5003 AUDIO_SOURCE_MIC,
5004 AUDIO_INPUT_FLAG_NONE,
5005 &input);
5006 if (status != NO_ERROR) {
5007 ALOGW("Cannot open input stream for device %s on hw module %s",
5008 availProfileDevices.toString().c_str(),
5009 hwModule->getName());
5010 continue;
5011 }
5012 for (const auto &device : availProfileDevices) {
5013 // give a valid ID to an attached device once confirmed it is reachable
5014 if (!device->isAttached()) {
5015 device->attach(hwModule);
5016 device->importAudioPortAndPickAudioProfile(inProfile, true);
5017 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005018 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005019 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5020 }
5021 }
5022 inputDesc->close();
5023 }
5024 }
5025}
5026
Eric Laurent98e38192018-02-15 18:31:53 -08005027void AudioPolicyManager::addOutput(audio_io_handle_t output,
5028 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005029{
Eric Laurent1c333e22014-05-20 10:48:17 -07005030 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005031 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005032 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005033 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005035}
5036
François Gaffie53615e22015-03-19 09:24:12 +01005037void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5038{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005039 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5040 ALOGV("%s: removing primary output", __func__);
5041 mPrimaryOutput = nullptr;
5042 }
François Gaffie53615e22015-03-19 09:24:12 +01005043 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005044 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005045}
5046
Eric Laurent98e38192018-02-15 18:31:53 -08005047void AudioPolicyManager::addInput(audio_io_handle_t input,
5048 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005049{
Eric Laurent1c333e22014-05-20 10:48:17 -07005050 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005052}
Eric Laurente552edb2014-03-10 17:42:56 -07005053
François Gaffie11d30102018-11-02 16:09:09 +01005054status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005055 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005056 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005057{
François Gaffie11d30102018-11-02 16:09:09 +01005058 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005059 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005061
François Gaffie11d30102018-11-02 16:09:09 +01005062 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005063 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005064 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005065 }
Eric Laurente552edb2014-03-10 17:42:56 -07005066
Eric Laurent3b73df72014-03-11 09:06:29 -07005067 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005068 // first call getAudioPort to get the supported attributes from the HAL
5069 struct audio_port_v7 port = {};
5070 device->toAudioPort(&port);
5071 status_t status = mpClientInterface->getAudioPort(&port);
5072 if (status == NO_ERROR) {
5073 device->importAudioPort(port);
5074 }
5075
5076 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005077 for (size_t i = 0; i < mOutputs.size(); i++) {
5078 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005079 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005080 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005081 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5082 mOutputs.keyAt(i), device->toString().c_str());
5083 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005084 }
5085 }
5086 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005087 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005088 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005089 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5090 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005091 if (profile->supportsDevice(device)) {
5092 profiles.add(profile);
5093 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5094 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005095 }
5096 }
5097 }
5098
Eric Laurent7b279bb2015-12-14 10:18:23 -08005099 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005100
Eric Laurente552edb2014-03-10 17:42:56 -07005101 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005102 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005103 return BAD_VALUE;
5104 }
5105
5106 // open outputs for matching profiles if needed. Direct outputs are also opened to
5107 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5108 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005109 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005110
5111 // nothing to do if one output is already opened for this profile
5112 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005113 for (j = 0; j < outputs.size(); j++) {
5114 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005115 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005116 // matching profile: save the sample rates, format and channel masks supported
5117 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005118 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005119 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005120 }
Eric Laurente552edb2014-03-10 17:42:56 -07005121 break;
5122 }
5123 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005124 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005125 continue;
5126 }
5127
Eric Laurent3974e3b2017-12-07 17:58:43 -08005128 if (!profile->canOpenNewIo()) {
5129 ALOGW("Max Output number %u already opened for this profile %s",
5130 profile->maxOpenCount, profile->getTagName().c_str());
5131 continue;
5132 }
5133
Eric Laurent83efe1c2017-07-09 16:51:08 -07005134 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005135 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005136 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5137 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005138 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005139 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005140 profiles.removeAt(profile_index);
5141 profile_index--;
5142 } else {
5143 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005144 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005145 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005146 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5147 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005148 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005149 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005150
François Gaffie11d30102018-11-02 16:09:09 +01005151 if (device_distinguishes_on_address(deviceType)) {
5152 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5153 device->toString().c_str());
5154 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5155 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005156 }
Eric Laurente552edb2014-03-10 17:42:56 -07005157 ALOGV("checkOutputsForDevice(): adding output %d", output);
5158 }
5159 }
5160
5161 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005162 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005163 return BAD_VALUE;
5164 }
Eric Laurentd4692962014-05-05 18:13:44 -07005165 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005166 // check if one opened output is not needed any more after disconnecting one device
5167 for (size_t i = 0; i < mOutputs.size(); i++) {
5168 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005169 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005170 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005171 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005172 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005173 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005174 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005175 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5176 mOutputs.keyAt(i));
5177 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005178 }
Eric Laurente552edb2014-03-10 17:42:56 -07005179 }
5180 }
Eric Laurentd4692962014-05-05 18:13:44 -07005181 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005182 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005183 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5184 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005185 if (!profile->supportsDevice(device)) {
5186 continue;
5187 }
5188 ALOGV("checkOutputsForDevice(): "
5189 "clearing direct output profile %zu on module %s",
5190 j, hwModule->getName());
5191 profile->clearAudioProfiles();
5192 if (!profile->hasDynamicAudioProfile()) {
5193 continue;
5194 }
5195 // When a device is disconnected, if there is an IOProfile that contains dynamic
5196 // profiles and supports the disconnected device, call getAudioPort to repopulate
5197 // the capabilities of the devices that is supported by the IOProfile.
5198 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5199 if (supportedDevice == device ||
5200 !mAvailableOutputDevices.contains(supportedDevice)) {
5201 continue;
5202 }
5203 struct audio_port_v7 port;
5204 supportedDevice->toAudioPort(&port);
5205 status_t status = mpClientInterface->getAudioPort(&port);
5206 if (status == NO_ERROR) {
5207 supportedDevice->importAudioPort(port);
5208 }
Eric Laurente552edb2014-03-10 17:42:56 -07005209 }
5210 }
5211 }
5212 }
5213 return NO_ERROR;
5214}
5215
François Gaffie11d30102018-11-02 16:09:09 +01005216status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005217 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005218{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005219 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005220
François Gaffie11d30102018-11-02 16:09:09 +01005221 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005222 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005223 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005224 }
5225
Eric Laurentd4692962014-05-05 18:13:44 -07005226 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005227 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005229 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005230 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005231 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005232 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005233 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005234
François Gaffie11d30102018-11-02 16:09:09 +01005235 if (profile->supportsDevice(device)) {
5236 profiles.add(profile);
5237 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5238 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005239 }
5240 }
5241 }
5242
Eric Laurent0dd51852019-04-19 18:18:58 -07005243 if (profiles.isEmpty()) {
5244 ALOGW("%s: No input profile available for device %s",
5245 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005246 return BAD_VALUE;
5247 }
5248
5249 // open inputs for matching profiles if needed. Direct inputs are also opened to
5250 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5251 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5252
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005254
Eric Laurentd4692962014-05-05 18:13:44 -07005255 // nothing to do if one input is already opened for this profile
5256 size_t input_index;
5257 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5258 desc = mInputs.valueAt(input_index);
5259 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005260 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005261 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005262 }
Eric Laurentd4692962014-05-05 18:13:44 -07005263 break;
5264 }
5265 }
5266 if (input_index != mInputs.size()) {
5267 continue;
5268 }
5269
Eric Laurent3974e3b2017-12-07 17:58:43 -08005270 if (!profile->canOpenNewIo()) {
5271 ALOGW("Max Input number %u already opened for this profile %s",
5272 profile->maxOpenCount, profile->getTagName().c_str());
5273 continue;
5274 }
5275
Eric Laurentfe231122017-11-17 17:48:06 -08005276 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005277 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005278 status_t status = desc->open(nullptr,
5279 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005280 AUDIO_SOURCE_MIC,
5281 AUDIO_INPUT_FLAG_NONE,
5282 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005283
Eric Laurentcf2c0212014-07-25 16:20:43 -07005284 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005285 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005286 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005287 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005288 mpClientInterface->setParameters(input, String8(param));
5289 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005290 }
François Gaffie11d30102018-11-02 16:09:09 +01005291 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005292 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005293 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005294 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005295 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005296 }
5297
Eric Laurent0dd51852019-04-19 18:18:58 -07005298 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005299 addInput(input, desc);
5300 }
5301 } // endif input != 0
5302
Eric Laurentcf2c0212014-07-25 16:20:43 -07005303 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005304 ALOGW("%s could not open input for device %s", __func__,
5305 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005306 profiles.removeAt(profile_index);
5307 profile_index--;
5308 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005309 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005310 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005311 }
Eric Laurentd4692962014-05-05 18:13:44 -07005312 ALOGV("checkInputsForDevice(): adding input %d", input);
5313 }
5314 } // end scan profiles
5315
5316 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005317 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005318 return BAD_VALUE;
5319 }
5320 } else {
5321 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005322 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005323 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005324 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005325 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005326 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005327 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005328 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005329 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5330 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005331 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005332 }
5333 }
5334 }
5335 } // end disconnect
5336
5337 return NO_ERROR;
5338}
5339
5340
Eric Laurente0720872014-03-11 09:30:41 -07005341void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005342{
5343 ALOGV("closeOutput(%d)", output);
5344
François Gaffie1c878552018-11-22 16:53:21 +01005345 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5346 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005347 ALOGW("closeOutput() unknown output %d", output);
5348 return;
5349 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005350 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005351 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005352
Eric Laurente552edb2014-03-10 17:42:56 -07005353 // look for duplicated outputs connected to the output being removed.
5354 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005355 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5356 if (dupOutput->isDuplicated() &&
5357 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5358 sp<SwAudioOutputDescriptor> remainingOutput =
5359 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005360 // As all active tracks on duplicated output will be deleted,
5361 // and as they were also referenced on the other output, the reference
5362 // count for their stream type must be adjusted accordingly on
5363 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005364 const bool wasActive = remainingOutput->isActive();
5365 // Note: no-op on the closing output where all clients has already been set inactive
5366 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005367 // stop() will be a no op if the output is still active but is needed in case all
5368 // active streams refcounts where cleared above
5369 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005370 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005371 }
Eric Laurente552edb2014-03-10 17:42:56 -07005372 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5373 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5374
5375 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005376 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005377 }
5378 }
5379
Eric Laurent05b90f82014-08-27 15:32:29 -07005380 nextAudioPortGeneration();
5381
François Gaffie1c878552018-11-22 16:53:21 +01005382 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005383 if (index >= 0) {
5384 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005385 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5386 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005387 mAudioPatches.removeItemsAt(index);
5388 mpClientInterface->onAudioPatchListUpdate();
5389 }
5390
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005391 if (closingOutputWasActive) {
5392 closingOutput->stop();
5393 }
François Gaffie1c878552018-11-22 16:53:21 +01005394 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005395
François Gaffie53615e22015-03-19 09:24:12 +01005396 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005397 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005398
5399 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5400 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005401 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005402 bool directOutputOpen = false;
5403 for (size_t i = 0; i < mOutputs.size(); i++) {
5404 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5405 directOutputOpen = true;
5406 break;
5407 }
5408 }
5409 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005410 ALOGV("no direct outputs open, reset MSD patches");
5411 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5412 // how output devices for patching are resolved. Avoid by caching and reusing the
5413 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5414 // devices to patch to. This may be complicated by the fact that devices may become
5415 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005416 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005417 }
5418 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005419}
5420
5421void AudioPolicyManager::closeInput(audio_io_handle_t input)
5422{
5423 ALOGV("closeInput(%d)", input);
5424
5425 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5426 if (inputDesc == NULL) {
5427 ALOGW("closeInput() unknown input %d", input);
5428 return;
5429 }
5430
Eric Laurent6a94d692014-05-20 11:18:06 -07005431 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005432
François Gaffie11d30102018-11-02 16:09:09 +01005433 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005434 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005435 if (index >= 0) {
5436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5438 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005439 mAudioPatches.removeItemsAt(index);
5440 mpClientInterface->onAudioPatchListUpdate();
5441 }
5442
Eric Laurentfe231122017-11-17 17:48:06 -08005443 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005444 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005445
François Gaffie11d30102018-11-02 16:09:09 +01005446 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5447 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005448 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005449 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005450 }
Eric Laurente552edb2014-03-10 17:42:56 -07005451}
5452
François Gaffie11d30102018-11-02 16:09:09 +01005453SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5454 const DeviceVector &devices,
5455 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005456{
5457 SortedVector<audio_io_handle_t> outputs;
5458
François Gaffie11d30102018-11-02 16:09:09 +01005459 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005460 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005461 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005462 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005463 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005464 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005465 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005466 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005467 outputs.add(openOutputs.keyAt(i));
5468 }
5469 }
5470 return outputs;
5471}
5472
Mikhail Naganov37977152018-07-11 15:54:44 -07005473void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5474{
5475 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5476 // output is suspended before any tracks are moved to it
5477 checkA2dpSuspend();
5478 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005479 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005480 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005481 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005482 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005483 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5484 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5485 // configuration changes will ultimately be rerouted correctly. We can still avoid
5486 // unnecessary rerouting by caching and reusing the arguments to
5487 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5488 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005489 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005490 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005491 // an event that changed routing likely occurred, inform upper layers
5492 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005493}
5494
François Gaffiec005e562018-11-06 15:04:49 +01005495bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5496 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005497{
François Gaffiec005e562018-11-06 15:04:49 +01005498 return mEngine->getProductStrategyForAttributes(lAttr) ==
5499 mEngine->getProductStrategyForAttributes(rAttr);
5500}
5501
Francois Gaffieff1eb522020-05-06 18:37:04 +02005502void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5503{
5504 for (size_t i = 0; i < mAudioSources.size(); i++) {
5505 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5506 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005507 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5508 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005509 connectAudioSource(sourceDesc);
5510 }
5511 }
5512}
5513
5514void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5515{
5516 for (size_t i = 0; i < mAudioSources.size(); i++) {
5517 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5518 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5519 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5520 disconnectAudioSource(sourceDesc);
5521 }
5522 }
5523}
5524
François Gaffiec005e562018-11-06 15:04:49 +01005525void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5526{
5527 auto psId = mEngine->getProductStrategyForAttributes(attr);
5528
5529 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5530 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005531
François Gaffie11d30102018-11-02 16:09:09 +01005532 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5533 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005534
Eric Laurentc209fe42020-06-05 18:11:23 -07005535 uint32_t maxLatency = 0;
5536 bool invalidate = false;
5537 // take into account dynamic audio policies related changes: if a client is now associated
5538 // to a different policy mix than at creation time, invalidate corresponding stream
5539 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5540 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5541 if (desc->isDuplicated()) {
5542 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005543 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005544 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5545 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5546 continue;
5547 }
5548 sp<AudioPolicyMix> primaryMix;
5549 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5550 client->flags(), primaryMix, nullptr);
5551 if (status != OK) {
5552 continue;
5553 }
yucliuf4de36d2020-09-14 14:57:56 -07005554 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005555 invalidate = true;
5556 if (desc->isStrategyActive(psId)) {
5557 maxLatency = desc->latency();
5558 }
5559 break;
5560 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005561 }
5562 }
5563
Eric Laurentc209fe42020-06-05 18:11:23 -07005564 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005565 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5566 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005567 for (audio_io_handle_t srcOut : srcOutputs) {
5568 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005569 if (desc == nullptr) continue;
5570
5571 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005572 maxLatency = desc->latency();
5573 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005574
5575 if (invalidate) continue;
5576
5577 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005578 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005579 // a client on a non direct outputs has necessarily a linear PCM format
5580 // so we can call selectOutput() safely
5581 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5582 client->flags(),
5583 client->config().format,
5584 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005585 client->config().sample_rate,
5586 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005587 if (newOutput != srcOut) {
5588 invalidate = true;
5589 break;
5590 }
5591 } else {
5592 sp<IOProfile> profile = getProfileForOutput(newDevices,
5593 client->config().sample_rate,
5594 client->config().format,
5595 client->config().channel_mask,
5596 client->flags(),
5597 true /* directOnly */);
5598 if (profile != desc->mProfile) {
5599 invalidate = true;
5600 break;
5601 }
5602 }
5603 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005604 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005605
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005606 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005607 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005608 std::to_string(srcOutputs[0]).c_str(),
5609 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005610 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005611 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005612 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005613 if (desc == nullptr) continue;
5614
5615 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005616 setStrategyMute(psId, true, desc);
5617 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005618 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005619 }
François Gaffiec005e562018-11-06 15:04:49 +01005620 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005621 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005622 connectAudioSource(source);
5623 }
Eric Laurente552edb2014-03-10 17:42:56 -07005624 }
5625
François Gaffiec005e562018-11-06 15:04:49 +01005626 // Move effects associated to this stream from previous output to new output
5627 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005628 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005629 }
François Gaffiec005e562018-11-06 15:04:49 +01005630 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005631 if (invalidate) {
5632 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5633 mpClientInterface->invalidateStream(stream);
5634 }
Eric Laurente552edb2014-03-10 17:42:56 -07005635 }
5636 }
5637}
5638
Eric Laurente0720872014-03-11 09:30:41 -07005639void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005640{
François Gaffiec005e562018-11-06 15:04:49 +01005641 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5642 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5643 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005644 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005645 }
Eric Laurente552edb2014-03-10 17:42:56 -07005646}
5647
Kevin Rocard153f92d2018-12-18 18:33:28 -08005648void AudioPolicyManager::checkSecondaryOutputs() {
5649 std::set<audio_stream_type_t> streamsToInvalidate;
5650 for (size_t i = 0; i < mOutputs.size(); i++) {
5651 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5652 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005653 sp<AudioPolicyMix> primaryMix;
5654 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005655 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005656 client->flags(), primaryMix, &secondaryMixes);
5657 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5658 for (auto &secondaryMix : secondaryMixes) {
5659 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5660 if (outputDesc != nullptr &&
5661 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5662 secondaryDescs.push_back(outputDesc);
5663 }
5664 }
5665
Kevin Rocard94114a22019-04-01 19:38:23 -07005666 if (status != OK ||
5667 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005668 client->getSecondaryOutputs().end(),
5669 secondaryDescs.begin(), secondaryDescs.end())) {
5670 streamsToInvalidate.insert(client->stream());
5671 }
5672 }
5673 }
5674 for (audio_stream_type_t stream : streamsToInvalidate) {
5675 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5676 mpClientInterface->invalidateStream(stream);
5677 }
5678}
5679
Eric Laurent2517af32020-11-25 15:31:27 +01005680bool AudioPolicyManager::isScoRequestedForComm() const {
5681 AudioDeviceTypeAddrVector devices;
5682 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5683 for (const auto &device : devices) {
5684 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5685 return true;
5686 }
5687 }
5688 return false;
5689}
5690
Eric Laurente0720872014-03-11 09:30:41 -07005691void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005692{
François Gaffie53615e22015-03-19 09:24:12 +01005693 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005694 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005695 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005696 return;
5697 }
5698
Eric Laurent3a4311c2014-03-17 12:00:47 -07005699 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005700 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5701 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005702 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005703
5704 // if suspended, restore A2DP output if:
5705 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005706 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005707 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005708 //
Eric Laurentf732e072016-08-03 19:30:28 -07005709 // if not suspended, suspend A2DP output if:
5710 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005711 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005712 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005713 //
5714 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005715 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005716 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005717 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005718 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005719
5720 mpClientInterface->restoreOutput(a2dpOutput);
5721 mA2dpSuspended = false;
5722 }
5723 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005724 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005725 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005726 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005727 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005728
5729 mpClientInterface->suspendOutput(a2dpOutput);
5730 mA2dpSuspended = true;
5731 }
5732 }
5733}
5734
François Gaffie11d30102018-11-02 16:09:09 +01005735DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5736 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005737{
François Gaffie11d30102018-11-02 16:09:09 +01005738 DeviceVector devices;
5739
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005740 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005741 if (index >= 0) {
5742 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005743 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005744 ALOGV("%s device %s forced by patch %d", __func__,
5745 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5746 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005747 }
5748 }
5749
Dean Wheatley514b4312020-06-17 21:45:00 +10005750 // Do not retrieve engine device for outputs through MSD
5751 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5752 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5753 return outputDesc->devices();
5754 }
5755
Eric Laurent97ac8712018-07-27 18:59:02 -07005756 // Honor explicit routing requests only if no client using default routing is active on this
5757 // input: a specific app can not force routing for other apps by setting a preferred device.
5758 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005759 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005760 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005761 if (device != nullptr) {
5762 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005763 }
5764
François Gaffiea807ef92018-11-05 10:44:33 +01005765 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5766 // of setForceUse / Default Bus device here
5767 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5768 if (device != nullptr) {
5769 return DeviceVector(device);
5770 }
5771
François Gaffiec005e562018-11-06 15:04:49 +01005772 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5773 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5774 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305775 auto hasStreamActive = [&](auto stream) {
5776 return hasStream(streams, stream) && isStreamActive(stream, 0);
5777 };
Eric Laurent484e9272018-06-07 17:29:23 -07005778
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305779 auto doGetOutputDevicesForVoice = [&]() {
5780 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5781 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5782 (isInCall() ||
5783 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
5784 };
5785
5786 // With low-latency playing on speaker, music on WFD, when the first low-latency
5787 // output is stopped, getNewOutputDevices checks for a product strategy
5788 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
5789 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
5790 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5791 // stream is associated to the output descriptor.
5792 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5793 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5794 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5795 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005796 // Retrieval of devices for voice DL is done on primary output profile, cannot
5797 // check the route (would force modifying configuration file for this profile)
5798 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5799 break;
5800 }
Eric Laurente552edb2014-03-10 17:42:56 -07005801 }
François Gaffiec005e562018-11-06 15:04:49 +01005802 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005803 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005804}
5805
François Gaffie11d30102018-11-02 16:09:09 +01005806sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5807 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005808{
François Gaffie11d30102018-11-02 16:09:09 +01005809 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005810
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005811 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005812 if (index >= 0) {
5813 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005814 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005815 ALOGV("getNewInputDevice() device %s forced by patch %d",
5816 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5817 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005818 }
5819 }
5820
Eric Laurent97ac8712018-07-27 18:59:02 -07005821 // Honor explicit routing requests only if no client using default routing is active on this
5822 // input: a specific app can not force routing for other apps by setting a preferred device.
5823 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005824 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5825 if (device != nullptr) {
5826 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005827 }
5828
Eric Laurentdc95a252018-04-12 12:46:56 -07005829 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005830 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005831 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5832 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5833 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005834 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005835 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005836 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005837 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005838
Eric Laurente552edb2014-03-10 17:42:56 -07005839 return device;
5840}
5841
Eric Laurent794fde22016-03-11 09:50:45 -08005842bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5843 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005844 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005845}
5846
Eric Laurente0720872014-03-11 09:30:41 -07005847audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005848 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005849 // getOutputDevicesForStream's behavior for invalid streams.
5850 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5851 // device for music stream), but we want to return the empty set.
5852 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005853 return AUDIO_DEVICE_NONE;
5854 }
François Gaffie11d30102018-11-02 16:09:09 +01005855 DeviceVector activeDevices;
5856 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005857 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5858 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005859 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005860 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005861 }
François Gaffiec005e562018-11-06 15:04:49 +01005862 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005863 devices.merge(curDevices);
5864 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005865 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005866 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005867 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005868 }
5869 }
Eric Laurente552edb2014-03-10 17:42:56 -07005870 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005871
Eric Laurentb0688d62018-08-14 15:49:18 -07005872 // Favor devices selected on active streams if any to report correct device in case of
5873 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005874 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005875 devices = activeDevices;
5876 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005877 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5878 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005879 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005880 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005881 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005882 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005883 }
jiabin9a3361e2019-10-01 09:38:30 -07005884 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5885 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005886}
5887
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005888status_t AudioPolicyManager::getDevicesForAttributes(
5889 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5890 if (devices == nullptr) {
5891 return BAD_VALUE;
5892 }
5893 // check dynamic policies but only for primary descriptors (secondary not used for audible
5894 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005895 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005896 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005897 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005898 if (status != OK) {
5899 return status;
5900 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005901 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5902 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5903 devices->push_back(device);
5904 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005905 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005906 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5907 for (const auto& device : curDevices) {
5908 devices->push_back(device->getDeviceTypeAddr());
5909 }
5910 return NO_ERROR;
5911}
5912
Eric Laurente0720872014-03-11 09:30:41 -07005913void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005914 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005915 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005916 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005917 updateDevicesAndOutputs();
5918 break;
5919 default:
5920 break;
5921 }
5922}
5923
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005924uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005925
5926 // skip beacon mute management if a dedicated TTS output is available
5927 if (mTtsOutputAvailable) {
5928 return 0;
5929 }
5930
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005931 switch(event) {
5932 case STARTING_OUTPUT:
5933 mBeaconMuteRefCount++;
5934 break;
5935 case STOPPING_OUTPUT:
5936 if (mBeaconMuteRefCount > 0) {
5937 mBeaconMuteRefCount--;
5938 }
5939 break;
5940 case STARTING_BEACON:
5941 mBeaconPlayingRefCount++;
5942 break;
5943 case STOPPING_BEACON:
5944 if (mBeaconPlayingRefCount > 0) {
5945 mBeaconPlayingRefCount--;
5946 }
5947 break;
5948 }
5949
5950 if (mBeaconMuteRefCount > 0) {
5951 // any playback causes beacon to be muted
5952 return setBeaconMute(true);
5953 } else {
5954 // no other playback: unmute when beacon starts playing, mute when it stops
5955 return setBeaconMute(mBeaconPlayingRefCount == 0);
5956 }
5957}
5958
5959uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5960 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5961 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5962 // keep track of muted state to avoid repeating mute/unmute operations
5963 if (mBeaconMuted != mute) {
5964 // mute/unmute AUDIO_STREAM_TTS on all outputs
5965 ALOGV("\t muting %d", mute);
5966 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005967 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005968 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005969 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005970 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005971 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005972 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005973 maxLatency = latency;
5974 }
5975 }
5976 mBeaconMuted = mute;
5977 return maxLatency;
5978 }
5979 return 0;
5980}
5981
Eric Laurente0720872014-03-11 09:30:41 -07005982void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005983{
François Gaffiec005e562018-11-06 15:04:49 +01005984 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005985 mPreviousOutputs = mOutputs;
5986}
5987
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005988uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005989 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005990 uint32_t delayMs)
5991{
5992 // mute/unmute strategies using an incompatible device combination
5993 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5994 // if unmuting, unmute only after the specified delay
5995 if (outputDesc->isDuplicated()) {
5996 return 0;
5997 }
5998
5999 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006000 DeviceVector devices = outputDesc->devices();
6001 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006002
François Gaffiec005e562018-11-06 15:04:49 +01006003 auto productStrategies = mEngine->getOrderedProductStrategies();
6004 for (const auto &productStrategy : productStrategies) {
6005 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6006 DeviceVector curDevices =
6007 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6008 curDevices = curDevices.filter(outputDesc->supportedDevices());
6009 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006010 bool doMute = false;
6011
François Gaffiec005e562018-11-06 15:04:49 +01006012 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006013 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006014 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6015 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006016 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006017 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006018 }
Eric Laurent99401132014-05-07 19:48:15 -07006019 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006020 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006021 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006022 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006023 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006024 continue;
6025 }
François Gaffiec005e562018-11-06 15:04:49 +01006026 ALOGVV("%s() %s (curDevice %s)", __func__,
6027 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6028 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6029 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006030 if (mute) {
6031 // FIXME: should not need to double latency if volume could be applied
6032 // immediately by the audioflinger mixer. We must account for the delay
6033 // between now and the next time the audioflinger thread for this output
6034 // will process a buffer (which corresponds to one buffer size,
6035 // usually 1/2 or 1/4 of the latency).
6036 if (muteWaitMs < desc->latency() * 2) {
6037 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006038 }
6039 }
6040 }
6041 }
6042 }
6043 }
6044
Eric Laurent99401132014-05-07 19:48:15 -07006045 // temporary mute output if device selection changes to avoid volume bursts due to
6046 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006047 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006048 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6049 // temporary mute duration is conservatively set to 4 times the reported latency
6050 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6051 if (muteWaitMs < tempMuteWaitMs) {
6052 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006053 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006054 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6055 // make sure that we do not start the temporary mute period too early in case of
6056 // delayed device change
6057 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6058 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006059 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006060 }
6061 }
6062
Eric Laurente552edb2014-03-10 17:42:56 -07006063 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6064 if (muteWaitMs > delayMs) {
6065 muteWaitMs -= delayMs;
6066 usleep(muteWaitMs * 1000);
6067 return muteWaitMs;
6068 }
6069 return 0;
6070}
6071
François Gaffie11d30102018-11-02 16:09:09 +01006072uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6073 const DeviceVector &devices,
6074 bool force,
6075 int delayMs,
6076 audio_patch_handle_t *patchHandle,
6077 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006078{
François Gaffie11d30102018-11-02 16:09:09 +01006079 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006080 uint32_t muteWaitMs;
6081
6082 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006083 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6084 nullptr /* patchHandle */, requiresMuteCheck);
6085 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6086 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006087 return muteWaitMs;
6088 }
Eric Laurente552edb2014-03-10 17:42:56 -07006089
6090 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006091 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006092 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006093
François Gaffie11d30102018-11-02 16:09:09 +01006094 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6095
6096 if (!filteredDevices.isEmpty()) {
6097 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006098 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006099
6100 // if the outputs are not materially active, there is no need to mute.
6101 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006102 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006103 } else {
6104 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6105 muteWaitMs = 0;
6106 }
Eric Laurente552edb2014-03-10 17:42:56 -07006107
Eric Laurent79ea9582020-06-11 18:49:24 -07006108 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6109 // output profile or if new device is not supported AND previous device(s) is(are) still
6110 // available (otherwise reset device must be done on the output)
6111 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6112 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6113 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6114 // restore previous device after evaluating strategy mute state
6115 outputDesc->setDevices(prevDevices);
6116 return muteWaitMs;
6117 }
6118
Eric Laurente552edb2014-03-10 17:42:56 -07006119 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006120 // the requested device is AUDIO_DEVICE_NONE
6121 // OR the requested device is the same as current device
6122 // AND force is not specified
6123 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006124 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006125 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006126 !force && outputDesc->getPatchHandle() != 0) {
6127 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6128 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006129 return muteWaitMs;
6130 }
6131
François Gaffie11d30102018-11-02 16:09:09 +01006132 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006133
Eric Laurente552edb2014-03-10 17:42:56 -07006134 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006135 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006136 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006137 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006138 PatchBuilder patchBuilder;
6139 patchBuilder.addSource(outputDesc);
6140 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6141 for (const auto &filteredDevice : filteredDevices) {
6142 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006143 }
6144
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006145 // Add half reported latency to delayMs when muteWaitMs is null in order
6146 // to avoid disordered sequence of muting volume and changing devices.
6147 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6148 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006149 }
Eric Laurente552edb2014-03-10 17:42:56 -07006150
6151 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006152 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006153
6154 return muteWaitMs;
6155}
6156
Eric Laurentc75307b2015-03-17 15:29:32 -07006157status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006158 int delayMs,
6159 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006160{
Eric Laurent6a94d692014-05-20 11:18:06 -07006161 ssize_t index;
6162 if (patchHandle) {
6163 index = mAudioPatches.indexOfKey(*patchHandle);
6164 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006165 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006166 }
6167 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006168 return INVALID_OPERATION;
6169 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006170 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006171 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006172 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006173 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006174 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006175 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006176 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006177 return status;
6178}
6179
6180status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006181 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006182 bool force,
6183 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006184{
6185 status_t status = NO_ERROR;
6186
Eric Laurent1f2f2232014-06-02 12:01:23 -07006187 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006188 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6189 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006190
François Gaffie11d30102018-11-02 16:09:09 +01006191 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006192 PatchBuilder patchBuilder;
6193 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006194 // AUDIO_SOURCE_HOTWORD is for internal use only:
6195 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006196 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6197 auto result = usecase;
6198 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6199 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6200 }
6201 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006202 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006203 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006204 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006205 }
6206 }
6207 return status;
6208}
6209
Eric Laurent6a94d692014-05-20 11:18:06 -07006210status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6211 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006212{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006213 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006214 ssize_t index;
6215 if (patchHandle) {
6216 index = mAudioPatches.indexOfKey(*patchHandle);
6217 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006218 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006219 }
6220 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006221 return INVALID_OPERATION;
6222 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006223 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006224 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006225 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006226 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006227 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006228 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006229 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006230 return status;
6231}
6232
François Gaffie11d30102018-11-02 16:09:09 +01006233sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006234 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006235 audio_format_t& format,
6236 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006237 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006238{
6239 // Choose an input profile based on the requested capture parameters: select the first available
6240 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006241 //
6242 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6243 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006244
Glenn Kasten730b9262018-03-29 15:01:26 -07006245 sp<IOProfile> firstInexact;
6246 uint32_t updatedSamplingRate = 0;
6247 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6248 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006249 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006250 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006251 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006252 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006253 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006254 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006255 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006256 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006257 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006258 &channelMask /*updatedChannelMask*/,
6259 // FIXME ugly cast
6260 (audio_output_flags_t) flags,
6261 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006262 return profile;
6263 }
François Gaffie11d30102018-11-02 16:09:09 +01006264 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006265 samplingRate,
6266 &updatedSamplingRate,
6267 format,
6268 &updatedFormat,
6269 channelMask,
6270 &updatedChannelMask,
6271 // FIXME ugly cast
6272 (audio_output_flags_t) flags,
6273 false /*exactMatchRequiredForInputFlags*/)) {
6274 firstInexact = profile;
6275 }
6276
Eric Laurente552edb2014-03-10 17:42:56 -07006277 }
6278 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006279 if (firstInexact != nullptr) {
6280 samplingRate = updatedSamplingRate;
6281 format = updatedFormat;
6282 channelMask = updatedChannelMask;
6283 return firstInexact;
6284 }
Eric Laurente552edb2014-03-10 17:42:56 -07006285 return NULL;
6286}
6287
François Gaffieaaac0fd2018-11-22 17:56:39 +01006288float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6289 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006290 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006291 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006292{
jiabin9a3361e2019-10-01 09:38:30 -07006293 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006294
6295 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6296 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6297 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6298 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006299 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6300 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6301 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6302 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006303 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006304
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006305 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006306 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6307 mOutputs.isActive(ringVolumeSrc, 0)) {
6308 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006309 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006310 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006311 }
6312
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006313 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006314 if ((volumeSource != callVolumeSrc && (isInCall() ||
6315 mOutputs.isActiveLocally(callVolumeSrc))) &&
6316 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6317 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6318 volumeSource == alarmVolumeSrc ||
6319 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6320 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6321 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006322 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006323 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006324 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006325 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006326 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006327 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006328 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6329 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6330 // programmatically muted.
6331 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6332 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6333 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006334 bool exemptFromCapping =
6335 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6336 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006337 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6338 volumeSource, volumeDb);
6339 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006340 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6341 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6342 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006343 }
6344 }
Eric Laurente552edb2014-03-10 17:42:56 -07006345 // if a headset is connected, apply the following rules to ring tones and notifications
6346 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006347 // - always attenuate notifications volume by 6dB
6348 // - attenuate ring tones volume by 6dB unless music is not playing and
6349 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006350 // - if music is playing, always limit the volume to current music volume,
6351 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006352 if (!Intersection(deviceTypes,
6353 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6354 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006355 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6356 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006357 ((volumeSource == alarmVolumeSrc ||
6358 volumeSource == ringVolumeSrc) ||
6359 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6360 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6361 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6362 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6363 curves.canBeMuted()) {
6364
Eric Laurente552edb2014-03-10 17:42:56 -07006365 // when the phone is ringing we must consider that music could have been paused just before
6366 // by the music application and behave as if music was active if the last music track was
6367 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006368 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006369 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006370 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006371 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006372 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6373 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006374 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006375 float musicVolDb = computeVolume(musicCurves,
6376 musicVolumeSrc,
6377 musicCurves.getVolumeIndex(musicDevice),
6378 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006379 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6380 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6381 if (volumeDb > minVolDb) {
6382 volumeDb = minVolDb;
6383 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006384 }
jiabin9a3361e2019-10-01 09:38:30 -07006385 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6386 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006387 // on A2DP, also ensure notification volume is not too low compared to media when
6388 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006389 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006390 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006391 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6392 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006393 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6394 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006395 }
6396 }
jiabin9a3361e2019-10-01 09:38:30 -07006397 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006398 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006399 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006400 }
6401 }
6402
François Gaffie43c73442018-11-08 08:21:55 +01006403 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006404}
6405
Eric Laurent3839bc02018-07-10 18:33:34 -07006406int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006407 VolumeSource fromVolumeSource,
6408 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006409{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006410 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006411 return srcIndex;
6412 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006413 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6414 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006415 float minSrc = (float)srcCurves.getVolumeIndexMin();
6416 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6417 float minDst = (float)dstCurves.getVolumeIndexMin();
6418 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006419
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006420 // preserve mute request or correct range
6421 if (srcIndex < minSrc) {
6422 if (srcIndex == 0) {
6423 return 0;
6424 }
6425 srcIndex = minSrc;
6426 } else if (srcIndex > maxSrc) {
6427 srcIndex = maxSrc;
6428 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006429 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6430}
6431
François Gaffieaaac0fd2018-11-22 17:56:39 +01006432status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6433 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006434 int index,
6435 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006436 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006437 int delayMs,
6438 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006439{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006440 // do not change actual attributes volume if the attributes is muted
6441 if (outputDesc->isMuted(volumeSource)) {
6442 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6443 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006444 return NO_ERROR;
6445 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006446 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6447 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6448 bool isVoiceVolSrc = callVolSrc == volumeSource;
6449 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6450
Eric Laurent2517af32020-11-25 15:31:27 +01006451 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006452 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006453 // if sco and call follow same curves, bypass forceUseForComm
6454 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006455 ((isVoiceVolSrc && isScoRequested) ||
6456 (isBtScoVolSrc && !isScoRequested))) {
6457 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6458 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006459 // Do not return an error here as AudioService will always set both voice call
6460 // and bluetooth SCO volumes due to stream aliasing.
6461 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006462 }
jiabin9a3361e2019-10-01 09:38:30 -07006463 if (deviceTypes.empty()) {
6464 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006465 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006466
jiabin9a3361e2019-10-01 09:38:30 -07006467 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6468 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006469 // Force VoIP volume to max for bluetooth SCO device except if muted
6470 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006471 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006472 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006473 }
jiabin9a3361e2019-10-01 09:38:30 -07006474 outputDesc->setVolume(
6475 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006476
François Gaffieaaac0fd2018-11-22 17:56:39 +01006477 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006478 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006479 // 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 +01006480 if (isVoiceVolSrc) {
6481 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006482 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006483 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006484 }
Eric Laurent18fba842016-03-31 14:41:26 -07006485 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006486 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6487 mLastVoiceVolume = voiceVolume;
6488 }
6489 }
Eric Laurente552edb2014-03-10 17:42:56 -07006490 return NO_ERROR;
6491}
6492
Eric Laurentc75307b2015-03-17 15:29:32 -07006493void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006494 const DeviceTypeSet& deviceTypes,
6495 int delayMs,
6496 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006497{
jiabincd510522020-01-22 09:40:55 -08006498 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006499 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6500 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6501 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006502 curves.getVolumeIndex(deviceTypes),
6503 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006504 }
6505}
6506
François Gaffiec005e562018-11-06 15:04:49 +01006507void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6508 bool on,
6509 const sp<AudioOutputDescriptor>& outputDesc,
6510 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006511 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006512{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006513 std::vector<VolumeSource> sourcesToMute;
6514 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6515 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6516 toString(attributes).c_str(), on, outputDesc->getId());
6517 VolumeSource source = toVolumeSource(attributes);
6518 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6519 sourcesToMute.push_back(source);
6520 }
Eric Laurente552edb2014-03-10 17:42:56 -07006521 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006522 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006523 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006524 }
6525
Eric Laurente552edb2014-03-10 17:42:56 -07006526}
6527
François Gaffieaaac0fd2018-11-22 17:56:39 +01006528void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6529 bool on,
6530 const sp<AudioOutputDescriptor>& outputDesc,
6531 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006532 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006533{
jiabin9a3361e2019-10-01 09:38:30 -07006534 if (deviceTypes.empty()) {
6535 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006536 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006537 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006538 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006539 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006540 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006541 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6542 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6543 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006544 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006545 }
6546 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006547 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6548 // ignored
6549 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006550 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006551 if (!outputDesc->isMuted(volumeSource)) {
6552 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006553 return;
6554 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006555 if (outputDesc->decMuteCount(volumeSource) == 0) {
6556 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006557 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006558 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006559 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006560 delayMs);
6561 }
6562 }
6563}
6564
François Gaffie53615e22015-03-19 09:24:12 +01006565bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6566{
François Gaffiec005e562018-11-06 15:04:49 +01006567 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006568 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6569 return true;
6570 }
6571
6572 // has known usage?
6573 switch (paa->usage) {
6574 case AUDIO_USAGE_UNKNOWN:
6575 case AUDIO_USAGE_MEDIA:
6576 case AUDIO_USAGE_VOICE_COMMUNICATION:
6577 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6578 case AUDIO_USAGE_ALARM:
6579 case AUDIO_USAGE_NOTIFICATION:
6580 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6581 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6582 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6583 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6584 case AUDIO_USAGE_NOTIFICATION_EVENT:
6585 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6586 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6587 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6588 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006589 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006590 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006591 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006592 case AUDIO_USAGE_EMERGENCY:
6593 case AUDIO_USAGE_SAFETY:
6594 case AUDIO_USAGE_VEHICLE_STATUS:
6595 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006596 break;
6597 default:
6598 return false;
6599 }
6600 return true;
6601}
6602
François Gaffie2110e042015-03-24 08:41:51 +01006603audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6604{
6605 return mEngine->getForceUse(usage);
6606}
6607
6608bool AudioPolicyManager::isInCall()
6609{
6610 return isStateInCall(mEngine->getPhoneState());
6611}
6612
6613bool AudioPolicyManager::isStateInCall(int state)
6614{
6615 return is_state_in_call(state);
6616}
6617
Eric Laurent74b71512019-11-06 17:21:57 -08006618bool AudioPolicyManager::isCallAudioAccessible()
6619{
6620 audio_mode_t mode = mEngine->getPhoneState();
6621 return (mode == AUDIO_MODE_IN_CALL)
6622 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6623 || (mode == AUDIO_MODE_CALL_SCREEN);
6624}
6625
Eric Laurentd60560a2015-04-10 11:31:20 -07006626void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6627{
6628 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006629 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006630 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006631 sourceDesc->sinkDevice()->equals(deviceDesc))
6632 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006633 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006634 }
6635 }
6636
6637 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6638 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6639 bool release = false;
6640 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6641 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6642 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6643 source->ext.device.type == deviceDesc->type()) {
6644 release = true;
6645 }
6646 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006647 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006648 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6649 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6650 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006651 sink->ext.device.type == deviceDesc->type() &&
6652 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6653 || strncmp(sink->ext.device.address, address,
6654 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006655 release = true;
6656 }
6657 }
6658 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006659 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6660 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006661 }
6662 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006663
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006664 mInputs.clearSessionRoutesForDevice(deviceDesc);
6665
Francois Gaffie716e1432019-01-14 16:58:59 +01006666 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006667}
6668
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006669void AudioPolicyManager::modifySurroundFormats(
6670 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006671 std::unordered_set<audio_format_t> enforcedSurround(
6672 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006673 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6674 for (const auto& pair : mConfig.getSurroundFormats()) {
6675 allSurround.insert(pair.first);
6676 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6677 }
Phil Burk09bc4612016-02-24 15:58:15 -08006678
6679 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6680 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006681 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006682 // This is the resulting set of formats depending on the surround mode:
6683 // 'all surround' = allSurround
6684 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6685 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6686 // 'manual surround' = mManualSurroundFormats
6687 // AUTO: formats v 'enforced surround'
6688 // ALWAYS: formats v 'all surround' v 'enforced surround'
6689 // NEVER: formats ^ 'non-surround'
6690 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006691
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006692 std::unordered_set<audio_format_t> formatSet;
6693 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6694 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006695 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006696 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006697 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006698 formatSet.insert(*formatIter);
6699 }
6700 }
6701 } else {
6702 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6703 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006704 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006705
jiabin81772902018-04-02 17:52:27 -07006706 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006707 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006708 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6709 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6710 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006711 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006712 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6713 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6714 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006715 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006716 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006717 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006718 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006719 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006720 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006721}
6722
jiabin06e4bab2019-07-29 10:13:34 -07006723void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6724 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006725 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6726 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6727
6728 // If NEVER, then remove support for channelMasks > stereo.
6729 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006730 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6731 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006732 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006733 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006734 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006735 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006736 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006737 }
6738 }
jiabin81772902018-04-02 17:52:27 -07006739 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6740 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6741 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006742 bool supports5dot1 = false;
6743 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006744 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006745 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6746 supports5dot1 = true;
6747 break;
6748 }
6749 }
6750 // If not then add 5.1 support.
6751 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006752 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006753 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006754 }
Phil Burk09bc4612016-02-24 15:58:15 -08006755 }
6756}
6757
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006758void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006759 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006760 AudioProfileVector &profiles)
6761{
6762 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006763 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006764
François Gaffie112b0af2015-11-19 16:13:25 +01006765 // Format MUST be checked first to update the list of AudioProfile
6766 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006767 reply = mpClientInterface->getParameters(
6768 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006769 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006770 AudioParameter repliedParameters(reply);
6771 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006772 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006773 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6774 return;
6775 }
Phil Burk09bc4612016-02-24 15:58:15 -08006776 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006777 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006778 if (device == AUDIO_DEVICE_OUT_HDMI
6779 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006780 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006781 }
jiabin3e277cc2019-09-10 14:27:34 -07006782 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006783 }
François Gaffie112b0af2015-11-19 16:13:25 +01006784
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006785 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006786 ChannelMaskSet channelMasks;
6787 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006788 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006789 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006790
6791 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006792 reply = mpClientInterface->getParameters(
6793 ioHandle,
6794 requestedParameters.toString() + ";" +
6795 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006796 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006797 AudioParameter repliedParameters(reply);
6798 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006799 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006800 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006801 }
6802 }
6803 if (profiles.hasDynamicChannelsFor(format)) {
6804 reply = mpClientInterface->getParameters(ioHandle,
6805 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006806 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006807 ALOGV("%s: supported channel masks %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::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006811 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006812 if (device == AUDIO_DEVICE_OUT_HDMI
6813 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006814 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006815 }
François Gaffie112b0af2015-11-19 16:13:25 +01006816 }
6817 }
jiabin3e277cc2019-09-10 14:27:34 -07006818 addDynamicAudioProfileAndSort(
6819 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006820 }
6821}
Eric Laurentd60560a2015-04-10 11:31:20 -07006822
Mikhail Naganovdc769682018-05-04 15:34:08 -07006823status_t AudioPolicyManager::installPatch(const char *caller,
6824 audio_patch_handle_t *patchHandle,
6825 AudioIODescriptorInterface *ioDescriptor,
6826 const struct audio_patch *patch,
6827 int delayMs)
6828{
6829 ssize_t index = mAudioPatches.indexOfKey(
6830 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6831 *patchHandle : ioDescriptor->getPatchHandle());
6832 sp<AudioPatch> patchDesc;
6833 status_t status = installPatch(
6834 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6835 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006836 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006837 }
6838 return status;
6839}
6840
6841status_t AudioPolicyManager::installPatch(const char *caller,
6842 ssize_t index,
6843 audio_patch_handle_t *patchHandle,
6844 const struct audio_patch *patch,
6845 int delayMs,
6846 uid_t uid,
6847 sp<AudioPatch> *patchDescPtr)
6848{
6849 sp<AudioPatch> patchDesc;
6850 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6851 if (index >= 0) {
6852 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006853 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006854 }
6855
6856 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6857 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6858 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6859 if (status == NO_ERROR) {
6860 if (index < 0) {
6861 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006862 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006863 } else {
6864 patchDesc->mPatch = *patch;
6865 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006866 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006867 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006868 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006869 }
6870 nextAudioPortGeneration();
6871 mpClientInterface->onAudioPatchListUpdate();
6872 }
6873 if (patchDescPtr) *patchDescPtr = patchDesc;
6874 return status;
6875}
6876
jiabinbce0c1d2020-10-05 11:20:18 -07006877bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6878{
6879 const TrackClientVector activeClients = output->getActiveClients();
6880 if (activeClients.empty()) {
6881 return true;
6882 }
6883 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6884 if (index < 0) {
6885 ALOGE("%s, no audio patch found while there are active clients on output %d",
6886 __func__, output->getId());
6887 return false;
6888 }
6889 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6890 DeviceVector routedDevices;
6891 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6892 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6893 patchDesc->mPatch.sinks[i].id);
6894 if (device == nullptr) {
6895 ALOGE("%s, no audio device found with id(%d)",
6896 __func__, patchDesc->mPatch.sinks[i].id);
6897 return false;
6898 }
6899 routedDevices.add(device);
6900 }
6901 for (const auto& client : activeClients) {
6902 // TODO: b/175343099 only travel the valid client
6903 sp<DeviceDescriptor> preferredDevice =
6904 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6905 if (mEngine->getOutputDevicesForAttributes(
6906 client->attributes(), preferredDevice, false) == routedDevices) {
6907 return false;
6908 }
6909 }
6910 return true;
6911}
6912
6913sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6914 const sp<IOProfile>& profile, const DeviceVector& devices)
6915{
6916 for (const auto& device : devices) {
6917 // TODO: This should be checking if the profile supports the device combo.
6918 if (!profile->supportsDevice(device)) {
6919 return nullptr;
6920 }
6921 }
6922 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6923 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6924 status_t status = desc->open(nullptr, devices,
6925 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6926 if (status != NO_ERROR) {
6927 return nullptr;
6928 }
6929
6930 // Here is where the out_set_parameters() for card & device gets called
6931 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6932 const audio_devices_t deviceType = device->type();
6933 const String8 &address = String8(device->address().c_str());
6934 if (!address.isEmpty()) {
6935 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6936 mpClientInterface->setParameters(output, String8(param));
6937 free(param);
6938 }
6939 updateAudioProfiles(device, output, profile->getAudioProfiles());
6940 if (!profile->hasValidAudioProfile()) {
6941 ALOGW("%s() missing param", __func__);
6942 desc->close();
6943 return nullptr;
6944 } else if (profile->hasDynamicAudioProfile()) {
6945 desc->close();
6946 output = AUDIO_IO_HANDLE_NONE;
6947 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6948 profile->pickAudioProfile(
6949 config.sample_rate, config.channel_mask, config.format);
6950 config.offload_info.sample_rate = config.sample_rate;
6951 config.offload_info.channel_mask = config.channel_mask;
6952 config.offload_info.format = config.format;
6953
6954 status = desc->open(&config, devices,
6955 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6956 if (status != NO_ERROR) {
6957 return nullptr;
6958 }
6959 }
6960
6961 addOutput(output, desc);
6962 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6963 sp<AudioPolicyMix> policyMix;
6964 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6965 policyMix->setOutput(desc);
6966 desc->mPolicyMix = policyMix;
6967 } else {
6968 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6969 address.string());
6970 }
6971
6972 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6973 // no duplicated output for direct outputs and
6974 // outputs used by dynamic policy mixes
6975 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6976
6977 //TODO: configure audio effect output stage here
6978
6979 // open a duplicating output thread for the new output and the primary output
6980 sp<SwAudioOutputDescriptor> dupOutputDesc =
6981 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6982 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6983 if (status == NO_ERROR) {
6984 // add duplicated output descriptor
6985 addOutput(duplicatedOutput, dupOutputDesc);
6986 } else {
6987 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6988 mPrimaryOutput->mIoHandle, output);
6989 desc->close();
6990 removeOutput(output);
6991 nextAudioPortGeneration();
6992 return nullptr;
6993 }
6994 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006995 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6996 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
6997 mPrimaryOutput = desc;
6998 }
jiabinbce0c1d2020-10-05 11:20:18 -07006999 return desc;
7000}
7001
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007002} // namespace android