blob: 6ef815d856562e2bd7f43ae71394ab05ba200e30 [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.
64static const std::vector<audio_format_t> compressedFormatsOrder = {{
65 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
66 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
67// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
68static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
69 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);
275 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100276 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700277 // do not force device change on duplicated output because if device is 0, it will
278 // also force a device 0 for the two outputs it is duplicated to which may override
279 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100280 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100281 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 // always force when disconnecting (a non-duplicated device)
284 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100285 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 }
jiabinbce0c1d2020-10-05 11:20:18 -0700287 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
288 desc->devices() != activeMediaDevices &&
289 desc->supportsDevicesForPlayback(activeMediaDevices)) {
290 // Reopen the output to query the dynamic profiles when there is not active
291 // clients or all active clients will be rerouted. Otherwise, set the flag
292 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
293 // can be reopened to query dynamic profiles when all clients are inactive.
294 if (areAllActiveTracksRerouted(desc)) {
295 outputsToReopen.push_back(mOutputs.keyAt(i));
296 } else {
297 desc->mPendingReopenToQueryProfiles = true;
298 }
299 }
300 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
301 // Clear the flag that previously set for re-querying profiles.
302 desc->mPendingReopenToQueryProfiles = false;
303 }
304 }
305 for (const auto& output : outputsToReopen) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
307 closeOutput(output);
308 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310
Eric Laurentd60560a2015-04-10 11:31:20 -0700311 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700322 switch (state)
323 {
324 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700330
331 if (mAvailableInputDevices.add(device) < 0) {
332 return NO_MEMORY;
333 }
334
François Gaffie44481e72016-04-20 07:49:57 +0200335 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
336 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200338
Eric Laurent0dd51852019-04-19 18:18:58 -0700339 if (checkInputsForDevice(device, state) != NO_ERROR) {
340 mAvailableInputDevices.remove(device);
341
François Gaffie11d30102018-11-02 16:09:09 +0100342 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100343
344 mHwModules.cleanUpForDevice(device);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 return INVALID_OPERATION;
347 }
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100354 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700355 return INVALID_OPERATION;
356 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700357
François Gaffie11d30102018-11-02 16:09:09 +0100358 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
360 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100361 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
François Gaffie11d30102018-11-02 16:09:09 +0100363 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700364
365 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100366
367 // remove device from mReportedFormatsMap cache
368 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 default:
François Gaffie11d30102018-11-02 16:09:09 +0100372 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700373 return BAD_VALUE;
374 }
375
Eric Laurent736a1022019-03-27 18:28:46 -0700376 // Propagate device availability to Engine
377 setEngineDeviceConnectionState(device, state);
378
Eric Laurent0dd51852019-04-19 18:18:58 -0700379 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700380 // As the input device list can impact the output device selection, update
381 // getDeviceForStrategy() cache
382 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Eric Laurent87ffa392015-05-22 10:32:38 -0700384 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100385 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
386 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700387 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200388 // Reconnect Audio Source
389 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
390 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
391 checkAudioSourceForAttributes(attributes);
392 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700393 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100394 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700395 }
396
Eric Laurentb52c1522014-05-20 11:27:36 -0700397 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700400
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return BAD_VALUE;
403}
404
Eric Laurent736a1022019-03-27 18:28:46 -0700405void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
406 audio_policy_dev_state_t state) {
407
408 // the Engine does not have to know about remote submix devices used by dynamic audio policies
409 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
410 return;
411 }
412 mEngine->setDeviceConnectionState(device, state);
413}
414
415
Eric Laurente0720872014-03-11 09:30:41 -0700416audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100417 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700418{
Eric Laurent634b7142016-04-20 13:48:02 -0700419 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800420 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
421 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700422 (strlen(device_address) != 0)/*matchAddress*/);
423
424 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100425 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700426 device, device_address);
427 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
428 }
François Gaffie53615e22015-03-19 09:24:12 +0100429
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 DeviceVector *deviceVector;
431
Eric Laurente552edb2014-03-10 17:42:56 -0700432 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700433 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700434 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 deviceVector = &mAvailableInputDevices;
436 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700438 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700439 }
Eric Laurent634b7142016-04-20 13:48:02 -0700440
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800441 return (deviceVector->getDevice(
442 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700443 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800444}
445
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800446status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
447 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800448 const char *device_name,
449 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800450{
451 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700452 String8 reply;
453 AudioParameter param;
454 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800455
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800456 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
457 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800458
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800459 // connect/disconnect only 1 device at a time
460 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
461
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700463 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800464 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800465 // Nothing to do: device is not connected
466 return NO_ERROR;
467 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800469
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700470 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800471 // configure codecs.
472 // Handle two specific cases by sending a set parameter to
473 // configure A2DP codecs. No need to toggle device state.
474 // Case 1: A2DP active device switches from primary to primary
475 // module
476 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200477 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700478 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800479 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
480 if (availablePrimaryOutputDevices().contains(devDesc) &&
481 (module != 0 && module->getHandle() == primaryHandle)) {
482 reply = mpClientInterface->getParameters(
483 AUDIO_IO_HANDLE_NONE,
484 String8(AudioParameter::keyReconfigA2dpSupported));
485 AudioParameter repliedParameters(reply);
486 repliedParameters.getInt(
487 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
488 if (isReconfigA2dpSupported) {
489 const String8 key(AudioParameter::keyReconfigA2dp);
490 param.add(key, String8("true"));
491 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
492 devDesc->setEncodedFormat(encodedFormat);
493 return NO_ERROR;
494 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700495 }
496 }
cnx421bd2dcc42020-07-11 14:58:44 +0800497 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
498 for (size_t i = 0; i < mOutputs.size(); i++) {
499 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
500 // mute media strategies and delay device switch by the largest
501 // This avoid sending the music tail into the earpiece or headset.
502 setStrategyMute(musicStrategy, true, desc);
503 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
504 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
505 nullptr, true /*fromCache*/).types());
506 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507 // Toggle the device state: UNAVAILABLE -> AVAILABLE
508 // This will force reading again the device configuration
509 status = setDeviceConnectionState(device,
510 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 device_address, device_name,
512 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513 if (status != NO_ERROR) {
514 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
515 status);
516 return status;
517 }
518
519 status = setDeviceConnectionState(device,
520 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522 if (status != NO_ERROR) {
523 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
524 status);
525 return status;
526 }
527
528 return NO_ERROR;
529}
530
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800531status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
532 std::vector<audio_format_t> *formats)
533{
534 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800535 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800536 std::unordered_set<audio_format_t> formatSet;
537 sp<HwModule> primaryModule =
538 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700539 if (primaryModule == nullptr) {
540 ALOGE("%s() unable to get primary module", __func__);
541 return NO_INIT;
542 }
jiabin9a3361e2019-10-01 09:38:30 -0700543 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
544 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800545 for (const auto& device : declaredDevices) {
546 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800547 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800548 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800549 return status;
550}
551
François Gaffie11d30102018-11-02 16:09:09 +0100552uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700553{
554 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100555 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700556 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700557
jiabin9a3361e2019-10-01 09:38:30 -0700558 if(!hasPrimaryOutput() ||
559 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700560 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700561 }
François Gaffie11d30102018-11-02 16:09:09 +0100562 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
563
Francois Gaffie716e1432019-01-14 16:58:59 +0100564 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100565 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100566 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100567
568 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100569 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700570
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200571 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700572 // release TX patch if any
573 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100574 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700575 mCallTxPatch.clear();
576 }
577
François Gaffie9eb18552018-11-05 10:33:26 +0100578 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700579 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100580 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700581 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100582 // retrieve Rx Source and Tx Sink device descriptors
583 sp<DeviceDescriptor> rxSourceDevice =
584 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
585 String8(),
586 AUDIO_FORMAT_DEFAULT);
587 sp<DeviceDescriptor> txSinkDevice =
588 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
589 String8(),
590 AUDIO_FORMAT_DEFAULT);
591
592 // RX and TX Telephony device are declared by Primary Audio HAL
593 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
594 (telephonyRxModule->getHalVersionMajor() >= 3)) {
595 if (rxSourceDevice == 0 || txSinkDevice == 0) {
596 // RX / TX Telephony device(s) is(are) not currently available
597 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
598 return muteWaitMs;
599 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100600 // createAudioPatchInternal now supports both HW / SW bridging
601 createRxPatch = true;
602 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100603 } else {
604 // If the RX device is on the primary HW module, then use legacy routing method for
605 // voice calls via setOutputDevice() on primary output.
606 // Otherwise, create two audio patches for TX and RX path.
607 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
608 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 // If the TX device is also on the primary HW module, setOutputDevice() will take care
610 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100611 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
612 (txSinkDevice != 0);
613 }
614 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
615 // Otherwise, create two audio patches for TX and RX path.
616 if (!createRxPatch) {
617 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700618 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200619 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800620 // If the TX device is on the primary HW module but RX device is
621 // on other HW module, SinkMetaData of telephony input should handle it
622 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700623 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700624 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100625 // terminate active capture if on the same HW module as the call TX source device
626 // FIXME: would be better to refine to only inputs whose profile connects to the
627 // call TX device but this information is not in the audio patch and logic here must be
628 // symmetric to the one in startInput()
629 for (const auto& activeDesc : mInputs.getActiveInputs()) {
630 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
631 closeActiveClients(activeDesc);
632 }
633 }
François Gaffie9eb18552018-11-05 10:33:26 +0100634 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800635 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700636
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800637 return muteWaitMs;
638}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700639
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800640sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100641 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700642 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700643
François Gaffie11d30102018-11-02 16:09:09 +0100644 if (device == nullptr) {
645 return nullptr;
646 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100647
648 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800649 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100650 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800651 addSource(mAvailableInputDevices.getDevice(
652 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800653 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100654 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800655 addSink(mAvailableOutputDevices.getDevice(
656 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800657 }
658
François Gaffieafd4cea2019-11-18 15:50:22 +0100659 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
660 status_t status =
661 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
662 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
663 if (status != NO_ERROR || index < 0) {
664 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
665 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800666 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100667 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800668}
669
Mikhail Naganov100f0122018-11-29 11:22:16 -0800670bool AudioPolicyManager::isDeviceOfModule(
671 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
672 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
673 if (module != 0) {
674 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
675 .indexOf(devDesc) != NAME_NOT_FOUND
676 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
677 .indexOf(devDesc) != NAME_NOT_FOUND;
678 }
679 return false;
680}
681
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200682void AudioPolicyManager::connectTelephonyRxAudioSource()
683{
684 disconnectTelephonyRxAudioSource();
685 const struct audio_port_config source = {
686 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
687 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
688 };
689 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
690 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
691 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
692}
693
694void AudioPolicyManager::disconnectTelephonyRxAudioSource()
695{
696 stopAudioSource(mCallRxSourceClientPort);
697 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
698}
699
Eric Laurente0720872014-03-11 09:30:41 -0700700void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700701{
702 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100703 // store previous phone state for management of sonification strategy below
704 int oldState = mEngine->getPhoneState();
705
706 if (mEngine->setPhoneState(state) != NO_ERROR) {
707 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700708 return;
709 }
François Gaffie2110e042015-03-24 08:41:51 +0100710 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700711 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700712 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700713 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800714 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700715 }
716
François Gaffie2110e042015-03-24 08:41:51 +0100717 /**
718 * Switching to or from incall state or switching between telephony and VoIP lead to force
719 * routing command.
720 */
Eric Laurent74b71512019-11-06 17:21:57 -0800721 bool force = ((isStateInCall(oldState) != isStateInCall(state))
722 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700723
724 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700725 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700726
Eric Laurente552edb2014-03-10 17:42:56 -0700727 int delayMs = 0;
728 if (isStateInCall(state)) {
729 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100730 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
731 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700732 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700733 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700734 // mute media and sonification strategies and delay device switch by the largest
735 // latency of any output where either strategy is active.
736 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100737 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
738 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
739 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700740 (delayMs < (int)desc->latency()*2)) {
741 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700742 }
François Gaffiec005e562018-11-06 15:04:49 +0100743 setStrategyMute(musicStrategy, true, desc);
744 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
745 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
746 nullptr, true /*fromCache*/).types());
747 setStrategyMute(sonificationStrategy, true, desc);
748 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
749 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
750 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700751 }
752 }
753
Eric Laurent87ffa392015-05-22 10:32:38 -0700754 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100755 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700756 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100757 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700758 // force routing command to audio hardware when ending call
759 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100760 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
761 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700762 }
Eric Laurente552edb2014-03-10 17:42:56 -0700763
Eric Laurent87ffa392015-05-22 10:32:38 -0700764 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100765 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700766 } else if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200767 disconnectTelephonyRxAudioSource();
Eric Laurent87ffa392015-05-22 10:32:38 -0700768 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700770 mCallTxPatch.clear();
771 }
François Gaffie11d30102018-11-02 16:09:09 +0100772 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700773 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100774 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700775 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700776 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700777
778 // reevaluate routing on all outputs in case tracks have been started during the call
779 for (size_t i = 0; i < mOutputs.size(); i++) {
780 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100781 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700782 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100783 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700784 }
785 }
786
Eric Laurente552edb2014-03-10 17:42:56 -0700787 if (isStateInCall(state)) {
788 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700789 // force reevaluating accessibility routing when call starts
790 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
792
793 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100794 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
795 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700796}
797
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700798audio_mode_t AudioPolicyManager::getPhoneState() {
799 return mEngine->getPhoneState();
800}
801
Eric Laurente0720872014-03-11 09:30:41 -0700802void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100803 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700804{
François Gaffie2110e042015-03-24 08:41:51 +0100805 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700806 if (config == mEngine->getForceUse(usage)) {
807 return;
808 }
Eric Laurente552edb2014-03-10 17:42:56 -0700809
François Gaffie2110e042015-03-24 08:41:51 +0100810 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
811 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
812 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
François Gaffie2110e042015-03-24 08:41:51 +0100814 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
815 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
816 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700817
818 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700819 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800820
Eric Laurent22fcda22019-05-17 16:28:47 -0700821 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
822 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
823 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
824 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
825 }
826
Eric Laurentdc462862016-07-19 12:29:53 -0700827 //FIXME: workaround for truncated touch sounds
828 // to be removed when the problem is handled by system UI
829 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700830 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
831 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
832 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700833
834 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100835 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700836}
837
Eric Laurente0720872014-03-11 09:30:41 -0700838void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700839{
840 ALOGV("setSystemProperty() property %s, value %s", property, value);
841}
842
Michael Chana94fbb22018-04-24 14:31:19 +1000843// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
844// search to profiles for direct outputs.
845sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100846 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000847 uint32_t samplingRate,
848 audio_format_t format,
849 audio_channel_mask_t channelMask,
850 audio_output_flags_t flags,
851 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700852{
Michael Chana94fbb22018-04-24 14:31:19 +1000853 if (directOnly) {
854 // only retain flags that will drive the direct output profile selection
855 // if explicitly requested
856 static const uint32_t kRelevantFlags =
857 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700858 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000859 flags =
860 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
861 }
Eric Laurent861a6282015-05-18 15:40:16 -0700862
863 sp<IOProfile> profile;
864
Mikhail Naganovd4120142017-12-06 15:49:22 -0800865 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800866 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100867 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700868 samplingRate, NULL /*updatedSamplingRate*/,
869 format, NULL /*updatedFormat*/,
870 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700871 flags)) {
872 continue;
873 }
874 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100875 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700876 continue;
877 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800878 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700879 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800880 continue;
881 }
Michael Chana94fbb22018-04-24 14:31:19 +1000882 if (!directOnly) return curProfile;
883 // when searching for direct outputs, if several profiles are compatible, give priority
884 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100885 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700886 continue;
887 }
888 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100889 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700890 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700891 }
Eric Laurente552edb2014-03-10 17:42:56 -0700892 }
893 }
Eric Laurent861a6282015-05-18 15:40:16 -0700894 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700895}
896
Eric Laurentf4e63452017-11-06 19:31:46 +0000897audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700898{
François Gaffiec005e562018-11-06 15:04:49 +0100899 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800900
901 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
902 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
903 // format, flags, etc. This may result in some discrepancy for functions that utilize
904 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
905 // and AudioSystem::getOutputSamplingRate().
906
François Gaffie11d30102018-11-02 16:09:09 +0100907 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700908 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700909
François Gaffie11d30102018-11-02 16:09:09 +0100910 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
911 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000912 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700913}
914
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700915status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
916 const audio_attributes_t *srcAttr,
917 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700918{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700919 if (srcAttr != NULL) {
920 if (!isValidAttributes(srcAttr)) {
921 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
922 __func__,
923 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
924 srcAttr->tags);
925 return BAD_VALUE;
926 }
927 *dstAttr = *srcAttr;
928 } else {
929 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
930 ALOGE("%s: invalid stream type", __func__);
931 return BAD_VALUE;
932 }
François Gaffiec005e562018-11-06 15:04:49 +0100933 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700934 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700935
936 // Only honor audibility enforced when required. The client will be
937 // forced to reconnect if the forced usage changes.
938 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700939 dstAttr->flags = static_cast<audio_flags_mask_t>(
940 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700941 }
942
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700943 return NO_ERROR;
944}
945
Kevin Rocard153f92d2018-12-18 18:33:28 -0800946status_t AudioPolicyManager::getOutputForAttrInt(
947 audio_attributes_t *resultAttr,
948 audio_io_handle_t *output,
949 audio_session_t session,
950 const audio_attributes_t *attr,
951 audio_stream_type_t *stream,
952 uid_t uid,
953 const audio_config_t *config,
954 audio_output_flags_t *flags,
955 audio_port_handle_t *selectedDeviceId,
956 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700957 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800958 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700959{
François Gaffiec005e562018-11-06 15:04:49 +0100960 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100961 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100962 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100963 const sp<DeviceDescriptor> requestedDevice =
964 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
965
Eric Laurent8a1095a2019-11-08 14:44:16 -0800966 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700967 status_t status = getAudioAttributes(resultAttr, attr, *stream);
968 if (status != NO_ERROR) {
969 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700970 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700971 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700972 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700973 }
François Gaffiec005e562018-11-06 15:04:49 +0100974 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700975
François Gaffiec005e562018-11-06 15:04:49 +0100976 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
977 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700978
Kevin Rocard153f92d2018-12-18 18:33:28 -0800979 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
980 // otherwise, fallback to the dynamic policies, if none match, query the engine.
981 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700982 sp<AudioPolicyMix> primaryMix;
983 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700984 if (status != OK) {
985 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800986 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700987
Kevin Rocard153f92d2018-12-18 18:33:28 -0800988 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700989 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800990
991 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700992 if ((usePrimaryOutputFromPolicyMixes
993 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800994 && !audio_is_linear_pcm(config->format)) {
995 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800996 return BAD_VALUE;
997 }
998 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700999 sp<DeviceDescriptor> deviceDesc =
1000 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1001 primaryMix->mDeviceAddress,
1002 AUDIO_FORMAT_DEFAULT);
1003 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001004 if (deviceDesc != nullptr
1005 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001006 audio_io_handle_t newOutput;
1007 status = openDirectOutput(
1008 *stream, session, config,
1009 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1010 DeviceVector(deviceDesc), &newOutput);
1011 if (status != NO_ERROR) {
1012 policyDesc = nullptr;
1013 } else {
1014 policyDesc = mOutputs.valueFor(newOutput);
1015 primaryMix->setOutput(policyDesc);
1016 }
1017 }
1018 if (policyDesc != nullptr) {
1019 policyDesc->mPolicyMix = primaryMix;
1020 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001021 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001022
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001023 ALOGV("getOutputForAttr() returns output %d", *output);
1024 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1025 *outputType = API_OUT_MIX_PLAYBACK;
1026 } else {
1027 *outputType = API_OUTPUT_LEGACY;
1028 }
1029 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001030 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001031 }
François Gaffiec005e562018-11-06 15:04:49 +01001032 // Virtual sources must always be dynamicaly or explicitly routed
1033 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1034 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1035 return BAD_VALUE;
1036 }
1037 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1038 // in order to let the choice of the order to future vendor engine
1039 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001040
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001041 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001042 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001043 }
1044
Nadav Barb2f18162018-07-18 13:01:53 +03001045 // Set incall music only if device was explicitly set, and fallback to the device which is
1046 // chosen by the engine if not.
1047 // FIXME: provide a more generic approach which is not device specific and move this back
1048 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001049 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001050 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001051 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001052 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001053 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001054 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001055 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001056 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001057 }
1058 }
1059
François Gaffiec005e562018-11-06 15:04:49 +01001060 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1061 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1062 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001063
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001064 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001065 if (!msdDevices.isEmpty()) {
1066 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Michael Chan6fb34492020-12-08 15:44:49 +11001067 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001068 ALOGV("%s() Using MSD devices %s instead of devices %s",
1069 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001070 } else {
1071 *output = AUDIO_IO_HANDLE_NONE;
1072 }
1073 }
1074 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001075 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001076 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001077 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001078 if (*output == AUDIO_IO_HANDLE_NONE) {
1079 return INVALID_OPERATION;
1080 }
Paul McLeanaa981192015-03-21 09:55:15 -07001081
François Gaffiec005e562018-11-06 15:04:49 +01001082 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001083 for (auto &outputDevice : outputDevices) {
1084 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1085 *selectedDeviceId = outputDevice->getId();
1086 break;
1087 }
1088 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001089
Eric Laurent8a1095a2019-11-08 14:44:16 -08001090 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1091 *outputType = API_OUTPUT_TELEPHONY_TX;
1092 } else {
1093 *outputType = API_OUTPUT_LEGACY;
1094 }
1095
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001096 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1097
1098 return NO_ERROR;
1099}
1100
1101status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1102 audio_io_handle_t *output,
1103 audio_session_t session,
1104 audio_stream_type_t *stream,
1105 uid_t uid,
1106 const audio_config_t *config,
1107 audio_output_flags_t *flags,
1108 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001110 std::vector<audio_io_handle_t> *secondaryOutputs,
1111 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001112{
1113 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1114 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1115 return INVALID_OPERATION;
1116 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001117 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001118 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001119 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001120 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001121 const sp<DeviceDescriptor> requestedDevice =
1122 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1123
1124 // Prevent from storing invalid requested device id in clients
1125 const audio_port_handle_t sanitizedRequestedPortId =
1126 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1127 *selectedDeviceId = sanitizedRequestedPortId;
1128
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001129 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001130 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001131 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001132 if (status != NO_ERROR) {
1133 return status;
1134 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001135 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001136 if (secondaryOutputs != nullptr) {
1137 for (auto &secondaryMix : secondaryMixes) {
1138 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1139 if (outputDesc != nullptr &&
1140 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1141 secondaryOutputs->push_back(outputDesc->mIoHandle);
1142 weakSecondaryOutputDescs.push_back(outputDesc);
1143 }
1144 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001145 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146
Eric Laurent8fc147b2018-07-22 19:13:55 -07001147 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001148 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001149 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001150 };
jiabin4ef93452019-09-10 14:29:54 -07001151 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001152
Eric Laurentc209fe42020-06-05 18:11:23 -07001153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001154 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001155 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001156 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001157 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001158 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001159 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001160 std::move(weakSecondaryOutputDescs),
1161 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001162 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001163
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001164 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1165 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001166
Eric Laurente83b55d2014-11-14 10:06:21 -08001167 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001168}
1169
Eric Laurentc529cf62020-04-17 18:19:10 -07001170status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1171 audio_session_t session,
1172 const audio_config_t *config,
1173 audio_output_flags_t flags,
1174 const DeviceVector &devices,
1175 audio_io_handle_t *output) {
1176
1177 *output = AUDIO_IO_HANDLE_NONE;
1178
1179 // skip direct output selection if the request can obviously be attached to a mixed output
1180 // and not explicitly requested
1181 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1182 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1183 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1184 return NAME_NOT_FOUND;
1185 }
1186
1187 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1188 // This prevents creating an offloaded track and tearing it down immediately after start
1189 // when audioflinger detects there is an active non offloadable effect.
1190 // FIXME: We should check the audio session here but we do not have it in this context.
1191 // This may prevent offloading in rare situations where effects are left active by apps
1192 // in the background.
1193 sp<IOProfile> profile;
1194 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1195 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1196 profile = getProfileForOutput(
1197 devices, config->sample_rate, config->format, config->channel_mask,
1198 flags, true /* directOnly */);
1199 }
1200
1201 if (profile == nullptr) {
1202 return NAME_NOT_FOUND;
1203 }
1204
1205 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1206 for (size_t i = 0; i < mOutputs.size(); i++) {
1207 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1208 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1209 // reuse direct output if currently open by the same client
1210 // and configured with same parameters
1211 if ((config->sample_rate == desc->getSamplingRate()) &&
1212 (config->format == desc->getFormat()) &&
1213 (config->channel_mask == desc->getChannelMask()) &&
1214 (session == desc->mDirectClientSession)) {
1215 desc->mDirectOpenCount++;
1216 ALOGI("%s reusing direct output %d for session %d", __func__,
1217 mOutputs.keyAt(i), session);
1218 *output = mOutputs.keyAt(i);
1219 return NO_ERROR;
1220 }
1221 }
1222 }
1223
1224 if (!profile->canOpenNewIo()) {
1225 return NAME_NOT_FOUND;
1226 }
1227
1228 sp<SwAudioOutputDescriptor> outputDesc =
1229 new SwAudioOutputDescriptor(profile, mpClientInterface);
1230
Michael Chan6fb34492020-12-08 15:44:49 +11001231 // An MSD patch may be using the only output stream that can service this request. Release
1232 // all MSD patches to prioritize this request over any active output on MSD.
1233 releaseMsdPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001234
1235 status_t status = outputDesc->open(config, devices, stream, flags, output);
1236
1237 // only accept an output with the requested parameters
1238 if (status != NO_ERROR ||
1239 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1240 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1241 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1242 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1243 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1244 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1245 config->channel_mask, outputDesc->getChannelMask());
1246 if (*output != AUDIO_IO_HANDLE_NONE) {
1247 outputDesc->close();
1248 }
1249 // fall back to mixer output if possible when the direct output could not be open
1250 if (audio_is_linear_pcm(config->format) &&
1251 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1252 return NAME_NOT_FOUND;
1253 }
1254 *output = AUDIO_IO_HANDLE_NONE;
1255 return BAD_VALUE;
1256 }
1257 outputDesc->mDirectOpenCount = 1;
1258 outputDesc->mDirectClientSession = session;
1259
1260 addOutput(*output, outputDesc);
1261 mPreviousOutputs = mOutputs;
1262 ALOGV("%s returns new direct output %d", __func__, *output);
1263 mpClientInterface->onAudioPortListUpdate();
1264 return NO_ERROR;
1265}
1266
François Gaffie11d30102018-11-02 16:09:09 +01001267audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1268 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001269 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001270 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001271 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001272 audio_output_flags_t *flags,
1273 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001274{
Andy Hungc88b0642018-04-27 15:42:35 -07001275 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001276
jiabine375d412019-02-26 12:54:53 -08001277 // Discard haptic channel mask when forcing muting haptic channels.
1278 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001279 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1280 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001281
Eric Laurente552edb2014-03-10 17:42:56 -07001282 // open a direct output if required by specified parameters
1283 //force direct flag if offload flag is set: offloading implies a direct output stream
1284 // and all common behaviors are driven by checking only the direct flag
1285 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001286 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1287 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001288 }
Nadav Bar766fb022018-01-07 12:18:03 +02001289 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1290 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001291 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001292 // only allow deep buffering for music stream type
1293 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001294 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001295 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001296 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001297 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1298 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001299 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001300 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001301 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001302 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001303 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001304 audio_is_linear_pcm(config->format) &&
1305 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001306 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001307 AUDIO_OUTPUT_FLAG_DIRECT);
1308 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001309 }
Eric Laurente552edb2014-03-10 17:42:56 -07001310
Eric Laurentc529cf62020-04-17 18:19:10 -07001311 audio_config_t directConfig = *config;
1312 directConfig.channel_mask = channelMask;
1313 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1314 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001315 return output;
1316 }
1317
Eric Laurent14cbfca2016-03-17 09:42:16 -07001318 // A request for HW A/V sync cannot fallback to a mixed output because time
1319 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001320 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001321 return AUDIO_IO_HANDLE_NONE;
1322 }
1323
Eric Laurente552edb2014-03-10 17:42:56 -07001324 // ignoring channel mask due to downmix capability in mixer
1325
1326 // open a non direct output
1327
1328 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001329 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001330 // get which output is suitable for the specified stream. The actual
1331 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001332 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001333
Eric Laurent8838a382014-09-08 16:44:28 -07001334 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001335 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001336 output = selectOutput(
1337 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001338 }
François Gaffie11d30102018-11-02 16:09:09 +01001339 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001340 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001341 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001342
Eric Laurente552edb2014-03-10 17:42:56 -07001343 return output;
1344}
1345
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001346sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001347 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1348 mAvailableInputDevices);
1349 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1350}
1351
1352DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1353 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1354 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001355}
1356
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001357const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1358 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001359 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1360 if (msdModule != 0) {
1361 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1362 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1363 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1364 const struct audio_port_config *source = &patch->mPatch.sources[j];
1365 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1366 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001367 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001368 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001369 }
1370 }
1371 }
1372 return msdPatches;
1373}
1374
François Gaffie11d30102018-11-02 16:09:09 +01001375status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001376 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1377{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001378 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001379 if (msdModule == nullptr) {
1380 ALOGE("%s() unable to get MSD module", __func__);
1381 return NO_INIT;
1382 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001383 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001384 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001385 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001386 return NO_INIT;
1387 }
1388 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1389 if (inputProfiles.isEmpty()) {
1390 ALOGE("%s() no input profiles for MSD module", __func__);
1391 return NO_INIT;
1392 }
1393 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1394 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001395 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001396 return NO_INIT;
1397 }
1398 AudioProfileVector msdProfiles;
1399 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1400 for (const auto &inProfile : inputProfiles) {
1401 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001402 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001403 }
1404 }
1405 AudioProfileVector deviceProfiles;
1406 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001407 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
1408 outProfile->supportsDevice(outputDevice)) {
jiabin3e277cc2019-09-10 14:27:34 -07001409 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 }
1411 }
1412 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001413 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001414 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001415 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001416 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001417 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1418 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001419 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001420 }
1421 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1422 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1423 sinkConfig->format = bestSinkConfig.format;
1424 // For encoded streams force direct flag to prevent downstream mixing.
1425 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1426 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001427 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1428 // For formats compatible with IEC61937 encapsulation, assume that
1429 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1430 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1431 // raw and IEC61937 framed streams.
1432 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1433 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1434 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001435 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1436 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1437 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1438 sourceConfig->format = bestSinkConfig.format;
1439 // Copy input stream directly without any processing (e.g. resampling).
1440 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1441 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1442 if (hwAvSync) {
1443 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1444 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1445 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1446 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1447 }
1448 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1449 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1450 sinkConfig->config_mask |= config_mask;
1451 sourceConfig->config_mask |= config_mask;
1452 return NO_ERROR;
1453}
1454
François Gaffie11d30102018-11-02 16:09:09 +01001455PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001456{
1457 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001458 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001459 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1460 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1461 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1462 // For now, we just forcefully try with HwAvSync first.
1463 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1464 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1465 getBestMsdAudioProfileFor(
1466 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1467 if (res == NO_ERROR) {
1468 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1469 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1470 }
1471 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1472 " supporting PCM format conversion.", __func__);
1473 return patchBuilder;
1474}
1475
Michael Chan6fb34492020-12-08 15:44:49 +11001476status_t AudioPolicyManager::setMsdPatches(const DeviceVector *outputDevices) {
1477 DeviceVector devices;
1478 if (outputDevices != nullptr && outputDevices->size() > 0) {
1479 devices.add(*outputDevices);
1480 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001481 // Use media strategy for unspecified output device. This should only
1482 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1483 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001484 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001485 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001486 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001487 }
Michael Chan6fb34492020-12-08 15:44:49 +11001488 std::vector<PatchBuilder> patchesToCreate;
1489 for (auto i = 0u; i < devices.size(); ++i) {
1490 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
1491 patchesToCreate.push_back(buildMsdPatch(devices[i]));
1492 }
1493 // Retain only the MSD patches associated with outputDevices request.
1494 // Tear down the others, and create new ones as needed.
1495 AudioPatchCollection patchesToRemove = getMsdPatches();
1496 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1497 auto retainedPatch = false;
1498 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1499 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1500 patchesToRemove.removeItemsAt(i);
1501 retainedPatch = true;
1502 break;
1503 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001504 }
Michael Chan6fb34492020-12-08 15:44:49 +11001505 if (retainedPatch) {
1506 it = patchesToCreate.erase(it);
1507 continue;
1508 }
1509 ++it;
1510 }
1511 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1512 return NO_ERROR;
1513 }
1514 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1515 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001516 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001517 }
Michael Chan6fb34492020-12-08 15:44:49 +11001518 status_t status = NO_ERROR;
1519 for (const auto &p : patchesToCreate) {
1520 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1521 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1522 char message[256];
1523 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1524 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1525 currStatus == NO_ERROR ? "Success" : "Error",
1526 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1527 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1528 if (currStatus == NO_ERROR) {
1529 ALOGD("%s", message);
1530 } else {
1531 ALOGE("%s", message);
1532 if (status == NO_ERROR) {
1533 status = currStatus;
1534 }
1535 }
1536 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537 return status;
1538}
1539
Michael Chan6fb34492020-12-08 15:44:49 +11001540void AudioPolicyManager::releaseMsdPatches(const DeviceVector& devices) {
1541 AudioPatchCollection msdPatches = getMsdPatches();
1542 for (size_t i = 0; i < msdPatches.size(); i++) {
1543 const auto& patch = msdPatches[i];
1544 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1545 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1546 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1547 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1548 releaseAudioPatch(patch->getHandle(), mUidCached);
1549 break;
1550 }
1551 }
1552 }
1553}
1554
Eric Laurente0720872014-03-11 09:30:41 -07001555audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001556 audio_output_flags_t flags,
1557 audio_format_t format,
1558 audio_channel_mask_t channelMask,
1559 uint32_t samplingRate,
1560 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001561{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001562 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1563 "%s called with format %#x", __func__, format);
1564
jiabinebb6af42020-06-09 17:31:17 -07001565 // Return the output that haptic-generating attached to when 1) session id is specified,
1566 // 2) haptic-generating effect exists for given session id and 3) the output that
1567 // haptic-generating effect attached to is in given outputs.
1568 if (sessionId != AUDIO_SESSION_NONE) {
1569 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1570 sessionId, FX_IID_HAPTICGENERATOR);
1571 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1572 return hapticGeneratingOutput;
1573 }
1574 }
1575
Eric Laurent16c66dd2019-05-01 17:54:10 -07001576 // Flags disqualifying an output: the match must happen before calling selectOutput()
1577 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1578 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1579
1580 // Flags expressing a functional request: must be honored in priority over
1581 // other criteria
1582 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1583 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1584 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1585 // Flags expressing a performance request: have lower priority than serving
1586 // requested sampling rate or channel mask
1587 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1588 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1589 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1590
1591 const audio_output_flags_t functionalFlags =
1592 (audio_output_flags_t)(flags & kFunctionalFlags);
1593 const audio_output_flags_t performanceFlags =
1594 (audio_output_flags_t)(flags & kPerformanceFlags);
1595
1596 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1597
Eric Laurente552edb2014-03-10 17:42:56 -07001598 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001599 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001600 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001601 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001602 // 2: the output with the highest number of requested functional flags
1603 // 3: the output supporting the exact channel mask
1604 // 4: the output with a higher channel count than requested
1605 // 5: the output with a higher sampling rate than requested
1606 // 6: the output with the highest number of requested performance flags
1607 // 7: the output with the bit depth the closest to the requested one
1608 // 8: the primary output
1609 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001610
Eric Laurent16c66dd2019-05-01 17:54:10 -07001611 // matching criteria values in priority order for best matching output so far
1612 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001613
Eric Laurent16c66dd2019-05-01 17:54:10 -07001614 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1615 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1616 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001617
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001618 for (audio_io_handle_t output : outputs) {
1619 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001620 // matching criteria values in priority order for current output
1621 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001622
Eric Laurent16c66dd2019-05-01 17:54:10 -07001623 if (outputDesc->isDuplicated()) {
1624 continue;
1625 }
1626 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1627 continue;
1628 }
Eric Laurent8838a382014-09-08 16:44:28 -07001629
Eric Laurent16c66dd2019-05-01 17:54:10 -07001630 // If haptic channel is specified, use the haptic output if present.
1631 // When using haptic output, same audio format and sample rate are required.
1632 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001633 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001634 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1635 continue;
1636 }
1637 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001638 && format == outputDesc->getFormat()
1639 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001640 currentMatchCriteria[0] = outputHapticChannelCount;
1641 }
1642
1643 // functional flags match
1644 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1645
1646 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001647 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1648 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001649 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1650 channelCount <= outputChannelCount) {
1651 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001652 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1653 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001654 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001655 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001656 currentMatchCriteria[3] = outputChannelCount;
1657 }
1658
1659 // sampling rate match
1660 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001661 samplingRate <= outputDesc->getSamplingRate()) {
1662 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001663 }
1664
1665 // performance flags match
1666 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1667
1668 // format match
1669 if (format != AUDIO_FORMAT_INVALID) {
1670 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001671 PolicyAudioPort::kFormatDistanceMax -
1672 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001673 }
1674
1675 // primary output match
1676 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1677
1678 // compare match criteria by priority then value
1679 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1680 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1681 bestMatchCriteria = currentMatchCriteria;
1682 bestOutput = output;
1683
1684 std::stringstream result;
1685 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1686 std::ostream_iterator<int>(result, " "));
1687 ALOGV("%s new bestOutput %d criteria %s",
1688 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001689 }
1690 }
1691
Eric Laurent16c66dd2019-05-01 17:54:10 -07001692 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001693}
1694
Eric Laurent8fc147b2018-07-22 19:13:55 -07001695status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001696{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001697 ALOGV("%s portId %d", __FUNCTION__, portId);
1698
1699 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1700 if (outputDesc == 0) {
1701 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001702 return BAD_VALUE;
1703 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001704 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001705
Eric Laurent8fc147b2018-07-22 19:13:55 -07001706 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001707 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001708
Eric Laurent733ce942017-12-07 12:18:25 -08001709 status_t status = outputDesc->start();
1710 if (status != NO_ERROR) {
1711 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001712 }
1713
Eric Laurent97ac8712018-07-27 18:59:02 -07001714 uint32_t delayMs;
1715 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001716
1717 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001718 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001719 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001720 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001721 if (delayMs != 0) {
1722 usleep(delayMs * 1000);
1723 }
1724
1725 return status;
1726}
1727
Eric Laurent97ac8712018-07-27 18:59:02 -07001728status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1729 const sp<TrackClientDescriptor>& client,
1730 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001731{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001732 // cannot start playback of STREAM_TTS if any other output is being used
1733 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001734
1735 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001736 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001737 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001738 auto clientStrategy = client->strategy();
1739 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001740 if (stream == AUDIO_STREAM_TTS) {
1741 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001742 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001743 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001744 return INVALID_OPERATION;
1745 } else {
1746 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1747 }
1748 } else {
1749 // some playback other than beacon starts
1750 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1751 }
1752
Eric Laurent77305a62016-07-25 16:39:22 -07001753 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001754 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001755 bool force = !outputDesc->isActive() &&
1756 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001757
François Gaffie11d30102018-11-02 16:09:09 +01001758 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001759 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001760 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001761 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001762 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001763 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001764 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001765 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001766 } else {
1767 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001768 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001769 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1770 AUDIO_FORMAT_DEFAULT);
1771 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1772 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001773 }
1774
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001775 // requiresMuteCheck is false when we can bypass mute strategy.
1776 // It covers a common case when there is no materially active audio
1777 // and muting would result in unnecessary delay and dropped audio.
1778 const uint32_t outputLatencyMs = outputDesc->latency();
1779 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1780
Eric Laurente552edb2014-03-10 17:42:56 -07001781 // increment usage count for this stream on the requested output:
1782 // NOTE that the usage count is the same for duplicated output and hardware output which is
1783 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001784 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001785
1786 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001787 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1788 client->isPreferredDeviceForExclusiveUse()) {
1789 // Preferred device may be exclusive, use only if no other active clients on this output
1790 devices = DeviceVector(
1791 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1792 } else {
1793 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1794 }
François Gaffie11d30102018-11-02 16:09:09 +01001795 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001796 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001797 }
1798 }
Eric Laurente552edb2014-03-10 17:42:56 -07001799
François Gaffiec005e562018-11-06 15:04:49 +01001800 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001801 selectOutputForMusicEffects();
1802 }
1803
François Gaffie1c878552018-11-22 16:53:21 +01001804 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001805 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001806 if (devices.isEmpty()) {
1807 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001808 }
François Gaffiec005e562018-11-06 15:04:49 +01001809 bool shouldWait =
1810 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1811 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1812 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001813 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001814 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001815 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001816 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001817 // An output has a shared device if
1818 // - managed by the same hw module
1819 // - supports the currently selected device
1820 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001821 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001822
Eric Laurent77305a62016-07-25 16:39:22 -07001823 // force a device change if any other output is:
1824 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001825 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001826 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001827 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001828 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001829 // change the device currently selected by the other output.
1830 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001831 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001832 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001833 force = true;
1834 }
1835 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001836 // a notification so that audio focus effect can propagate, or that a mute/unmute
1837 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001838 const uint32_t latencyMs = desc->latency();
1839 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1840
1841 if (shouldWait && isActive && (waitMs < latencyMs)) {
1842 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001843 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001844
1845 // Require mute check if another output is on a shared device
1846 // and currently active to have proper drain and avoid pops.
1847 // Note restoring AudioTracks onto this output needs to invoke
1848 // a volume ramp if there is no mute.
1849 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001850 }
1851 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001852
1853 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001854 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001855
Eric Laurente552edb2014-03-10 17:42:56 -07001856 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001857 auto &curves = getVolumeCurves(client->attributes());
1858 checkAndSetVolume(curves, client->volumeSource(),
1859 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001860 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001861 outputDesc->devices().types(), 0 /*delay*/,
1862 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001863
1864 // update the outputs if starting an output with a stream that can affect notification
1865 // routing
1866 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001867
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001868 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001869 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001870 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1871 }
Eric Laurentdc462862016-07-19 12:29:53 -07001872
1873 if (waitMs > muteWaitMs) {
1874 *delayMs = waitMs - muteWaitMs;
1875 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001876
1877 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1878 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1879 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1880 // change occurs after the MixerThread starts and causes a stream volume
1881 // glitch.
1882 //
1883 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001884 }
Eric Laurentdc462862016-07-19 12:29:53 -07001885
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001886 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001887 mEngine->getForceUse(
1888 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001889 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001890 }
1891
Eric Laurent97ac8712018-07-27 18:59:02 -07001892 // Automatically enable the remote submix input when output is started on a re routing mix
1893 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001894 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1895 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001896 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1897 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1898 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001899 "remote-submix",
1900 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001901 }
1902
Eric Laurente552edb2014-03-10 17:42:56 -07001903 return NO_ERROR;
1904}
1905
Eric Laurent8fc147b2018-07-22 19:13:55 -07001906status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001907{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001908 ALOGV("%s portId %d", __FUNCTION__, portId);
1909
1910 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1911 if (outputDesc == 0) {
1912 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001913 return BAD_VALUE;
1914 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001915 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001916
Eric Laurent97ac8712018-07-27 18:59:02 -07001917 ALOGV("stopOutput() output %d, stream %d, session %d",
1918 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001919
Eric Laurent97ac8712018-07-27 18:59:02 -07001920 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001921
Eric Laurent733ce942017-12-07 12:18:25 -08001922 if (status == NO_ERROR ) {
1923 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001924 }
1925 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001926}
1927
Eric Laurent97ac8712018-07-27 18:59:02 -07001928status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1929 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001930{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001931 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001932 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001933 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001934
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001935 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1936
François Gaffie1c878552018-11-22 16:53:21 +01001937 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1938 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001939 // Automatically disable the remote submix input when output is stopped on a
1940 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001941 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001942 if (isSingleDeviceType(
1943 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001944 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001945 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001946 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1947 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001948 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001949 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001950 }
1951 }
1952 bool forceDeviceUpdate = false;
1953 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001954 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001955 forceDeviceUpdate = true;
1956 }
1957
Eric Laurente552edb2014-03-10 17:42:56 -07001958 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001959 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001960
Eric Laurente552edb2014-03-10 17:42:56 -07001961 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001962 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001963 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001964 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001965 // delay the device switch by twice the latency because stopOutput() is executed when
1966 // the track stop() command is received and at that time the audio track buffer can
1967 // still contain data that needs to be drained. The latency only covers the audio HAL
1968 // and kernel buffers. Also the latency does not always include additional delay in the
1969 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001970 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001971
1972 // force restoring the device selection on other active outputs if it differs from the
1973 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001974 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001975 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001976 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001977 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001978 desc->isActive() &&
1979 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001980 (newDevices != desc->devices())) {
1981 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1982 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001983
François Gaffie11d30102018-11-02 16:09:09 +01001984 setOutputDevices(desc, newDevices2, force, delayMs);
1985
Eric Laurent57de36c2016-09-28 16:59:11 -07001986 // re-apply device specific volume if not done by setOutputDevice()
1987 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001988 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001989 }
Eric Laurente552edb2014-03-10 17:42:56 -07001990 }
1991 }
1992 // update the outputs if stopping one with a stream that can affect notification routing
1993 handleNotificationRoutingForStream(stream);
1994 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001995
1996 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1997 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001998 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001999 }
2000
François Gaffiec005e562018-11-06 15:04:49 +01002001 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002002 selectOutputForMusicEffects();
2003 }
Eric Laurente552edb2014-03-10 17:42:56 -07002004 return NO_ERROR;
2005 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002006 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002007 return INVALID_OPERATION;
2008 }
2009}
2010
jiabinbce0c1d2020-10-05 11:20:18 -07002011bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002012{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002013 ALOGV("%s portId %d", __FUNCTION__, portId);
2014
2015 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2016 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002017 // If an output descriptor is closed due to a device routing change,
2018 // then there are race conditions with releaseOutput from tracks
2019 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2020 // destroyed shortly thereafter.
2021 //
2022 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002023 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002024 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002025 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026
2027 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002028
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302029 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2030 if (outputDesc->isClientActive(client)) {
2031 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2032 stopOutput(portId);
2033 }
2034
Eric Laurent8fc147b2018-07-22 19:13:55 -07002035 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2036 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002037 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002038 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002039 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002040 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002041 if (--outputDesc->mDirectOpenCount == 0) {
2042 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002043 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002044 }
2045 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302046
Andy Hung39efb7a2018-09-26 15:39:28 -07002047 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002048 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2049 // The output is pending reopened to query dynamic profiles and
2050 // there is no active clients
2051 closeOutput(outputDesc->mIoHandle);
2052 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2053 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2054 if (newOutputDesc == nullptr) {
2055 ALOGE("%s failed to open output", __func__);
2056 }
2057 return true;
2058 }
2059 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002060}
2061
Eric Laurentcaf7f482014-11-25 17:50:47 -08002062status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2063 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002064 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002065 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002066 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002067 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002068 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002069 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002070 input_type_t *inputType,
2071 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002072{
François Gaffiec005e562018-11-06 15:04:49 +01002073 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2074 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2075 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002076
Eric Laurentad2e7b92017-09-14 20:06:42 -07002077 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002078 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002079 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002080 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002081 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002082 sp<AudioInputDescriptor> inputDesc;
2083 sp<RecordClientDescriptor> clientDesc;
2084 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002085 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086
2087 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2088 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2089 return INVALID_OPERATION;
2090 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002091
Francois Gaffie716e1432019-01-14 16:58:59 +01002092 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2093 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002094 }
2095
Paul McLean466dc8e2015-04-17 13:15:36 -06002096 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002097 sp<DeviceDescriptor> explicitRoutingDevice =
2098 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002099
Eric Laurentad2e7b92017-09-14 20:06:42 -07002100 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2101 // possible
2102 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2103 *input != AUDIO_IO_HANDLE_NONE) {
2104 ssize_t index = mInputs.indexOfKey(*input);
2105 if (index < 0) {
2106 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2107 status = BAD_VALUE;
2108 goto error;
2109 }
2110 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111 RecordClientVector clients = inputDesc->getClientsForSession(session);
2112 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002113 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2114 status = BAD_VALUE;
2115 goto error;
2116 }
2117 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2118 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002119 // corresponds to a new client and is only permitted from the same UID.
2120 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002121 if (clients.size() > 1) {
2122 for (const auto& client : clients) {
2123 // The client map is ordered by key values (portId) and portIds are allocated
2124 // incrementaly. So the first client in this list is the one opened by audio flinger
2125 // when the mmap stream is created and should be ignored as it does not correspond
2126 // to an actual client
2127 if (client == *clients.cbegin()) {
2128 continue;
2129 }
2130 if (uid != client->uid() && !client->isSilenced()) {
2131 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2132 uid, client->portId(), client->uid());
2133 status = INVALID_OPERATION;
2134 goto error;
2135 }
Eric Laurent331679c2018-04-16 17:03:16 -07002136 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002137 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002138 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002139 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002140
Eric Laurent8f42ea12018-08-08 09:08:25 -07002141 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002142 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002143 }
2144
2145 *input = AUDIO_IO_HANDLE_NONE;
2146 *inputType = API_INPUT_INVALID;
2147
Francois Gaffie716e1432019-01-14 16:58:59 +01002148 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002149
Francois Gaffie716e1432019-01-14 16:58:59 +01002150 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2151 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2152 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002153 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002154 ALOGW("%s could not find input mix for attr %s",
2155 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002156 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002157 }
jiabinc1de2df2019-05-07 14:26:40 -07002158 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2159 String8(attr->tags + strlen("addr=")),
2160 AUDIO_FORMAT_DEFAULT);
2161 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002162 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002163 __func__, attributes.source, attributes.tags);
2164 status = BAD_VALUE;
2165 goto error;
2166 }
2167
Kevin Rocard25f9b052019-02-27 15:08:54 -08002168 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2169 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2170 } else {
2171 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002173 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002174 if (explicitRoutingDevice != nullptr) {
2175 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002176 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002177 // Prevent from storing invalid requested device id in clients
2178 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002179 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 }
François Gaffie11d30102018-11-02 16:09:09 +01002181 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002182 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002183 status = BAD_VALUE;
2184 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002185 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002186 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2187 *inputType = API_INPUT_MIX_CAPTURE;
2188 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002189 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2190 // there is an external policy, but this input is attached to a mix of recorders,
2191 // meaning it receives audio injected into the framework, so the recorder doesn't
2192 // know about it and is therefore considered "legacy"
2193 *inputType = API_INPUT_LEGACY;
2194 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002195 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002196 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002197 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002198 } else {
2199 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002200 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002201
Eric Laurent599c7582015-12-07 18:05:55 -08002202 }
2203
François Gaffiec005e562018-11-06 15:04:49 +01002204 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002205 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002206 status = INVALID_OPERATION;
2207 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002208 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002209
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210exit:
2211
François Gaffiec005e562018-11-06 15:04:49 +01002212 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2213 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002214
Francois Gaffie716e1432019-01-14 16:58:59 +01002215 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002216 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002217 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218
Mikhail Naganov2996f672019-04-18 12:29:59 -07002219 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002220 requestedDeviceId, attributes.source, flags,
2221 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002222 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002223 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002224
2225 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2226 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002227
Eric Laurent599c7582015-12-07 18:05:55 -08002228 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002229
2230error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002231 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002232}
2233
2234
François Gaffie11d30102018-11-02 16:09:09 +01002235audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002236 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002237 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002238 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002239 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002240 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002241{
2242 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002243 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002244 bool isSoundTrigger = false;
2245
François Gaffiec005e562018-11-06 15:04:49 +01002246 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002247 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2248 if (index >= 0) {
2249 input = mSoundTriggerSessions.valueFor(session);
2250 isSoundTrigger = true;
2251 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2252 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2253 } else {
2254 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002255 }
François Gaffiec005e562018-11-06 15:04:49 +01002256 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002257 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002258 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002259 }
2260
Andy Hungf129b032015-04-07 13:45:50 -07002261 // find a compatible input profile (not necessarily identical in parameters)
2262 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002263 // sampling rate and flags may be updated by getInputProfile
2264 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2265 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002266 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002267 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002268 audio_input_flags_t profileFlags = flags;
2269 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002270 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002271 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002272 profileFlags);
2273 if (profile != 0) {
2274 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002275 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2276 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002277 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2278 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2279 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002280 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2281 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2282 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002283 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002284 }
Eric Laurente552edb2014-03-10 17:42:56 -07002285 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002286 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002287 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002288 if (samplingRate == 0) {
2289 samplingRate = profileSamplingRate;
2290 }
Eric Laurente552edb2014-03-10 17:42:56 -07002291
Eric Laurent322b4d22015-04-03 15:57:54 -07002292 if (profile->getModuleHandle() == 0) {
2293 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002294 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002295 }
2296
Eric Laurent3974e3b2017-12-07 17:58:43 -08002297 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002298 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002299 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002300 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002301 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002302 continue;
2303 }
2304 // if sound trigger, reuse input if used by other sound trigger on same session
2305 // else
2306 // reuse input if active client app is not in IDLE state
2307 //
2308 RecordClientVector clients = desc->clientsList();
2309 bool doClose = false;
2310 for (const auto& client : clients) {
2311 if (isSoundTrigger != client->isSoundTrigger()) {
2312 continue;
2313 }
2314 if (client->isSoundTrigger()) {
2315 if (session == client->session()) {
2316 return desc->mIoHandle;
2317 }
2318 continue;
2319 }
2320 if (client->active() && client->appState() != APP_STATE_IDLE) {
2321 return desc->mIoHandle;
2322 }
2323 doClose = true;
2324 }
2325 if (doClose) {
2326 closeInput(desc->mIoHandle);
2327 } else {
2328 i++;
2329 }
2330 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002331 }
2332
Eric Laurentfe231122017-11-17 17:48:06 -08002333 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002334
Eric Laurentfe231122017-11-17 17:48:06 -08002335 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2336 lConfig.sample_rate = profileSamplingRate;
2337 lConfig.channel_mask = profileChannelMask;
2338 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002339
François Gaffie11d30102018-11-02 16:09:09 +01002340 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002341
2342 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002343 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002344 (profileSamplingRate != lConfig.sample_rate) ||
2345 !audio_formats_match(profileFormat, lConfig.format) ||
2346 (profileChannelMask != lConfig.channel_mask)) {
2347 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002348 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002349 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002350 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002351 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002352 }
Eric Laurent599c7582015-12-07 18:05:55 -08002353 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
2355
Eric Laurentc722f302014-12-10 11:21:49 -08002356 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002357
Eric Laurent599c7582015-12-07 18:05:55 -08002358 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002359 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002360
Eric Laurent599c7582015-12-07 18:05:55 -08002361 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002362}
2363
Eric Laurent4eb58f12018-12-07 16:41:02 -08002364status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002365{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002366 ALOGV("%s portId %d", __FUNCTION__, portId);
2367
2368 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2369 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002370 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002371 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002372 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002373 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002374 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002375 if (client->active()) {
2376 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2377 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002378 }
2379
Eric Laurent8f42ea12018-08-08 09:08:25 -07002380 audio_session_t session = client->session();
2381
Eric Laurent4eb58f12018-12-07 16:41:02 -08002382 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002383
Eric Laurent4eb58f12018-12-07 16:41:02 -08002384 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002385
Eric Laurent4eb58f12018-12-07 16:41:02 -08002386 status_t status = inputDesc->start();
2387 if (status != NO_ERROR) {
2388 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002389 }
Eric Laurente552edb2014-03-10 17:42:56 -07002390
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002391 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002392 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002393 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002394
Eric Laurent8f42ea12018-08-08 09:08:25 -07002395 // indicate active capture to sound trigger service if starting capture from a mic on
2396 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002397 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002398 if (device != nullptr) {
2399 status = setInputDevice(input, device, true /* force */);
2400 } else {
2401 ALOGW("%s no new input device can be found for descriptor %d",
2402 __FUNCTION__, inputDesc->getId());
2403 status = BAD_VALUE;
2404 }
Eric Laurente552edb2014-03-10 17:42:56 -07002405
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002406 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002407 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002408 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002409 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002410 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2411 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002412 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002413 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002414
François Gaffie11d30102018-11-02 16:09:09 +01002415 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2416 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002417 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002418 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002419 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002420
Eric Laurent8f42ea12018-08-08 09:08:25 -07002421 // automatically enable the remote submix output when input is started if not
2422 // used by a policy mix of type MIX_TYPE_RECORDERS
2423 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002424 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002425 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002426 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002427 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002428 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2429 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002430 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431 if (address != "") {
2432 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2433 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002434 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002435 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002436 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002437 } else if (status != NO_ERROR) {
2438 // Restore client activity state.
2439 inputDesc->setClientActive(client, false);
2440 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002441 }
2442
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002443 ALOGV("%s input %d source = %d status = %d exit",
2444 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002445
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002446 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002447}
2448
Eric Laurent8fc147b2018-07-22 19:13:55 -07002449status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002450{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002451 ALOGV("%s portId %d", __FUNCTION__, portId);
2452
2453 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2454 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002456 return BAD_VALUE;
2457 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002458 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002459 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002460 if (!client->active()) {
2461 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002462 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002463 }
2464
Eric Laurent8f42ea12018-08-08 09:08:25 -07002465 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002466
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467 inputDesc->stop();
2468 if (inputDesc->isActive()) {
2469 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2470 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002471 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002472 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002473 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002474 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2475 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002476 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002477 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002478
2479 // automatically disable the remote submix output when input is stopped if not
2480 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002481 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002483 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002484 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002485 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2486 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 }
2488 if (address != "") {
2489 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2490 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002491 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 }
2493 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002494 resetInputDevice(input);
2495
2496 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2497 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002498 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2499 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002500 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002501 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 }
2503 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002504 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002505 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002506}
2507
Eric Laurent8fc147b2018-07-22 19:13:55 -07002508void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002509{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002510 ALOGV("%s portId %d", __FUNCTION__, portId);
2511
2512 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2513 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002515 return;
2516 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002517 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518 audio_io_handle_t input = inputDesc->mIoHandle;
2519
Eric Laurent8f42ea12018-08-08 09:08:25 -07002520 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002521
Andy Hung39efb7a2018-09-26 15:39:28 -07002522 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002523
Andy Hung39efb7a2018-09-26 15:39:28 -07002524 if (inputDesc->getClientCount() > 0) {
2525 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002526 return;
2527 }
2528
Eric Laurent05b90f82014-08-27 15:32:29 -07002529 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002530 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002532}
2533
Eric Laurent8f42ea12018-08-08 09:08:25 -07002534void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002535{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002536 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002537
2538 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002539 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002540 }
2541}
2542
Eric Laurent8f42ea12018-08-08 09:08:25 -07002543void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2544{
2545 stopInput(portId);
2546 releaseInput(portId);
2547}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002548
Eric Laurent0dd51852019-04-19 18:18:58 -07002549void AudioPolicyManager::checkCloseInputs() {
2550 // After connecting or disconnecting an input device, close input if:
2551 // - it has no client (was just opened to check profile) OR
2552 // - none of its supported devices are connected anymore OR
2553 // - one of its clients cannot be routed to one of its supported
2554 // devices anymore. Otherwise update device selection
2555 std::vector<audio_io_handle_t> inputsToClose;
2556 for (size_t i = 0; i < mInputs.size(); i++) {
2557 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2558 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002559 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002560 inputsToClose.push_back(mInputs.keyAt(i));
2561 } else {
2562 bool close = false;
2563 for (const auto& client : input->clientsList()) {
2564 sp<DeviceDescriptor> device =
2565 mEngine->getInputDeviceForAttributes(client->attributes());
2566 if (!input->supportedDevices().contains(device)) {
2567 close = true;
2568 break;
2569 }
2570 }
2571 if (close) {
2572 inputsToClose.push_back(mInputs.keyAt(i));
2573 } else {
2574 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2575 }
2576 }
2577 }
2578
2579 for (const audio_io_handle_t handle : inputsToClose) {
2580 ALOGV("%s closing input %d", __func__, handle);
2581 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002582 }
Eric Laurentd4692962014-05-05 18:13:44 -07002583}
2584
François Gaffie251c7f02018-11-07 10:41:08 +01002585void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002586{
2587 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002588 if (indexMin < 0 || indexMax < 0) {
2589 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2590 return;
2591 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002592 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002593
2594 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002595 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2596 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002597 continue;
2598 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002599 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002600 }
Eric Laurente552edb2014-03-10 17:42:56 -07002601}
2602
Eric Laurente0720872014-03-11 09:30:41 -07002603status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002604 int index,
2605 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002606{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002607 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002608 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2609 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2610 return NO_ERROR;
2611 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002612 ALOGV("%s: stream %s attributes=%s", __func__,
2613 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002614 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002615}
2616
Eric Laurente0720872014-03-11 09:30:41 -07002617status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002618 int *index,
2619 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002620{
François Gaffiec005e562018-11-06 15:04:49 +01002621 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2622 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002623 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002624 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002625 deviceTypes = mEngine->getOutputDevicesForStream(
2626 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002627 }
jiabin9a3361e2019-10-01 09:38:30 -07002628 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002629}
2630
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002631status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002632 int index,
2633 audio_devices_t device)
2634{
2635 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002636 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2637 if (group == VOLUME_GROUP_NONE) {
2638 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002639 return BAD_VALUE;
2640 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002641 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002642 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002643 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002644 VolumeSource vs = toVolumeSource(group);
2645 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2646
2647 status = setVolumeCurveIndex(index, device, curves);
2648 if (status != NO_ERROR) {
2649 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2650 return status;
2651 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002652
jiabin9a3361e2019-10-01 09:38:30 -07002653 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002654 auto curCurvAttrs = curves.getAttributes();
2655 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2656 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002657 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002658 } else if (!curves.getStreamTypes().empty()) {
2659 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002660 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002661 } else {
2662 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2663 return BAD_VALUE;
2664 }
jiabin9a3361e2019-10-01 09:38:30 -07002665 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2666 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002667
François Gaffiecfe17322018-11-07 13:41:29 +01002668 // update volume on all outputs and streams matching the following:
2669 // - The requested stream (or a stream matching for volume control) is active on the output
2670 // - The device (or devices) selected by the engine for this stream includes
2671 // the requested device
2672 // - For non default requested device, currently selected device on the output is either the
2673 // requested device or one of the devices selected by the engine for this stream
2674 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2675 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002676 for (size_t i = 0; i < mOutputs.size(); i++) {
2677 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002678 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002679
jiabin9a3361e2019-10-01 09:38:30 -07002680 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2681 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002682 }
François Gaffieed91f582020-01-31 10:35:37 +01002683 if (!(desc->isActive(vs) || isInCall())) {
2684 continue;
2685 }
2686 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2687 curDevices.find(device) == curDevices.end()) {
2688 continue;
2689 }
2690 bool applyVolume = false;
2691 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2692 curSrcDevices.insert(device);
2693 applyVolume = (curSrcDevices.find(
2694 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2695 } else {
2696 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2697 }
2698 if (!applyVolume) {
2699 continue; // next output
2700 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002701 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2702 // If a higher priority strategy is active, and the output is routed to a device with a
2703 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002704 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002705 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002706 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2707 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2708 false /*preferredDevice*/);
2709 if (activeClients.empty()) {
2710 continue;
2711 }
2712 bool isPreempted = false;
2713 bool isHigherPriority = productStrategy < strategy;
2714 for (const auto &client : activeClients) {
2715 if (isHigherPriority && (client->volumeSource() != vs)) {
2716 ALOGV("%s: Strategy=%d (\nrequester:\n"
2717 " group %d, volumeGroup=%d attributes=%s)\n"
2718 " higher priority source active:\n"
2719 " volumeGroup=%d attributes=%s) \n"
2720 " on output %zu, bailing out", __func__, productStrategy,
2721 group, group, toString(attributes).c_str(),
2722 client->volumeSource(), toString(client->attributes()).c_str(), i);
2723 applyVolume = false;
2724 isPreempted = true;
2725 break;
2726 }
2727 // However, continue for loop to ensure no higher prio clients running on output
2728 if (client->volumeSource() == vs) {
2729 applyVolume = true;
2730 }
2731 }
2732 if (isPreempted || applyVolume) {
2733 break;
2734 }
2735 }
2736 if (!applyVolume) {
2737 continue; // next output
2738 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002739 }
François Gaffieed91f582020-01-31 10:35:37 +01002740 //FIXME: workaround for truncated touch sounds
2741 // delayed volume change for system stream to be removed when the problem is
2742 // handled by system UI
2743 status_t volStatus = checkAndSetVolume(
2744 curves, vs, index, desc, curDevices,
2745 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2746 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2747 if (volStatus != NO_ERROR) {
2748 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002749 }
2750 }
François Gaffiecfe17322018-11-07 13:41:29 +01002751 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2752 return status;
2753}
2754
François Gaffieaaac0fd2018-11-22 17:56:39 +01002755status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002756 audio_devices_t device,
2757 IVolumeCurves &volumeCurves)
2758{
2759 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2760 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002761 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2762 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002763 (index > volumeCurves.getVolumeIndexMax())) {
2764 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2765 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2766 return BAD_VALUE;
2767 }
2768 if (!audio_is_output_device(device)) {
2769 return BAD_VALUE;
2770 }
2771
2772 // Force max volume if stream cannot be muted
2773 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2774
François Gaffieaaac0fd2018-11-22 17:56:39 +01002775 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002776 volumeCurves.addCurrentVolumeIndex(device, index);
2777 return NO_ERROR;
2778}
2779
2780status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2781 int &index,
2782 audio_devices_t device)
2783{
2784 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2785 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002786 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002787 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002788 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2789 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002790 }
jiabin9a3361e2019-10-01 09:38:30 -07002791 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002792}
2793
2794status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2795 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002796 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002797{
jiabin9a3361e2019-10-01 09:38:30 -07002798 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002799 return BAD_VALUE;
2800 }
jiabin9a3361e2019-10-01 09:38:30 -07002801 index = curves.getVolumeIndex(deviceTypes);
2802 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002803 return NO_ERROR;
2804}
2805
2806status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2807 int &index)
2808{
2809 index = getVolumeCurves(attr).getVolumeIndexMin();
2810 return NO_ERROR;
2811}
2812
2813status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2814 int &index)
2815{
2816 index = getVolumeCurves(attr).getVolumeIndexMax();
2817 return NO_ERROR;
2818}
2819
Eric Laurent36829f92017-04-07 19:04:42 -07002820audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002821{
2822 // select one output among several suitable for global effects.
2823 // The priority is as follows:
2824 // 1: An offloaded output. If the effect ends up not being offloadable,
2825 // AudioFlinger will invalidate the track and the offloaded output
2826 // will be closed causing the effect to be moved to a PCM output.
2827 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002828 // 3: The primary output
2829 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002830
François Gaffiec005e562018-11-06 15:04:49 +01002831 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2832 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002833 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002834
Eric Laurent36829f92017-04-07 19:04:42 -07002835 if (outputs.size() == 0) {
2836 return AUDIO_IO_HANDLE_NONE;
2837 }
Eric Laurente552edb2014-03-10 17:42:56 -07002838
Eric Laurent36829f92017-04-07 19:04:42 -07002839 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2840 bool activeOnly = true;
2841
2842 while (output == AUDIO_IO_HANDLE_NONE) {
2843 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2844 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2845 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2846
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002847 for (audio_io_handle_t output : outputs) {
2848 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002849 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002850 continue;
2851 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002852 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2853 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002854 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002855 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002856 }
2857 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002858 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002859 }
2860 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002861 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002862 }
2863 }
2864 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2865 output = outputOffloaded;
2866 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2867 output = outputDeepBuffer;
2868 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2869 output = outputPrimary;
2870 } else {
2871 output = outputs[0];
2872 }
2873 activeOnly = false;
2874 }
2875
2876 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002877 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002878 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2879 mMusicEffectOutput = output;
2880 }
2881
2882 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002883 return output;
2884}
2885
Eric Laurent36829f92017-04-07 19:04:42 -07002886audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2887{
2888 return selectOutputForMusicEffects();
2889}
2890
Eric Laurente0720872014-03-11 09:30:41 -07002891status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002892 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002893 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002894 int session,
2895 int id)
2896{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002897 if (session != AUDIO_SESSION_DEVICE) {
2898 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002899 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002900 index = mInputs.indexOfKey(io);
2901 if (index < 0) {
2902 ALOGW("registerEffect() unknown io %d", io);
2903 return INVALID_OPERATION;
2904 }
Eric Laurente552edb2014-03-10 17:42:56 -07002905 }
2906 }
François Gaffiec005e562018-11-06 15:04:49 +01002907 return mEffects.registerEffect(desc, io, session, id,
2908 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2909 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002910}
2911
Eric Laurentc241b0d2018-11-28 09:08:49 -08002912status_t AudioPolicyManager::unregisterEffect(int id)
2913{
2914 if (mEffects.getEffect(id) == nullptr) {
2915 return INVALID_OPERATION;
2916 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002917 if (mEffects.isEffectEnabled(id)) {
2918 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2919 setEffectEnabled(id, false);
2920 }
2921 return mEffects.unregisterEffect(id);
2922}
2923
2924status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2925{
2926 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2927 if (effect == nullptr) {
2928 return INVALID_OPERATION;
2929 }
2930
2931 status_t status = mEffects.setEffectEnabled(id, enabled);
2932 if (status == NO_ERROR) {
2933 mInputs.trackEffectEnabled(effect, enabled);
2934 }
2935 return status;
2936}
2937
Eric Laurent6c796322019-04-09 14:13:17 -07002938
2939status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2940{
2941 mEffects.moveEffects(ids, io);
2942 return NO_ERROR;
2943}
2944
Eric Laurentc75307b2015-03-17 15:29:32 -07002945bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2946{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002947 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002948}
2949
2950bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2951{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002952 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002953}
2954
Eric Laurente0720872014-03-11 09:30:41 -07002955bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002956{
2957 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002958 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002959 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002960 return true;
2961 }
2962 }
2963 return false;
2964}
2965
Eric Laurent275e8e92014-11-30 15:14:47 -08002966// Register a list of custom mixes with their attributes and format.
2967// When a mix is registered, corresponding input and output profiles are
2968// added to the remote submix hw module. The profile contains only the
2969// parameters (sampling rate, format...) specified by the mix.
2970// The corresponding input remote submix device is also connected.
2971//
2972// When a remote submix device is connected, the address is checked to select the
2973// appropriate profile and the corresponding input or output stream is opened.
2974//
2975// When capture starts, getInputForAttr() will:
2976// - 1 look for a mix matching the address passed in attribtutes tags if any
2977// - 2 if none found, getDeviceForInputSource() will:
2978// - 2.1 look for a mix matching the attributes source
2979// - 2.2 if none found, default to device selection by policy rules
2980// At this time, the corresponding output remote submix device is also connected
2981// and active playback use cases can be transferred to this mix if needed when reconnecting
2982// after AudioTracks are invalidated
2983//
2984// When playback starts, getOutputForAttr() will:
2985// - 1 look for a mix matching the address passed in attribtutes tags if any
2986// - 2 if none found, look for a mix matching the attributes usage
2987// - 3 if none found, default to device and output selection by policy rules.
2988
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002989status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002990{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002991 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2992 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002993 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002994 sp<HwModule> rSubmixModule;
2995 // examine each mix's route type
2996 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002997 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002998 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2999 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3000 ALOGE("Unsupported Policy Mix %zu of %zu: "
3001 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3002 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003003 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003004 break;
3005 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003006 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3007 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003008 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003009 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3010 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003011 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003012 rSubmixModule = mHwModules.getModuleFromName(
3013 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3014 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003015 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003016 i);
3017 res = INVALID_OPERATION;
3018 break;
3019 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003020 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003021
Eric Laurent97ac8712018-07-27 18:59:02 -07003022 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003023 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003024 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003025 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003026 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3027 } else {
3028 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3029 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003030 }
François Gaffie036e1e92015-03-19 10:16:24 +01003031
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003032 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003033 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003034 res = INVALID_OPERATION;
3035 break;
3036 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003037 audio_config_t outputConfig = mix.mFormat;
3038 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003039 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3040 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003041 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3042 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003043 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003044 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003045 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003046 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003047
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003048 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003049 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3050 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3051 ALOGE("Failed to set remote submix device available, type %u, address %s",
3052 mix.mDeviceType, address.string());
3053 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003054 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003055 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3056 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003057 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003058 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003059 i, mixes.size(), type, address.string());
3060
3061 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3062 mix.mDeviceType, mix.mDeviceAddress,
3063 String8(), AUDIO_FORMAT_DEFAULT);
3064 if (device == nullptr) {
3065 res = INVALID_OPERATION;
3066 break;
3067 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003068
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003069 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003070 // First try to find an already opened output supporting the device
3071 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003072 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003073
Eric Laurentc529cf62020-04-17 18:19:10 -07003074 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003075 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003076 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3077 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003078 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003079 } else {
3080 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003081 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003082 }
3083 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003084 // If no output found, try to find a direct output profile supporting the device
3085 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3086 sp<HwModule> module = mHwModules[i];
3087 for (size_t j = 0;
3088 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3089 j++) {
3090 sp<IOProfile> profile = module->getOutputProfiles()[j];
3091 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3092 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3093 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3094 address.string());
3095 res = INVALID_OPERATION;
3096 } else {
3097 foundOutput = true;
3098 }
3099 }
3100 }
3101 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003102 if (res != NO_ERROR) {
3103 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003104 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003105 res = INVALID_OPERATION;
3106 break;
3107 } else if (!foundOutput) {
3108 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003109 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003110 res = INVALID_OPERATION;
3111 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003112 } else {
3113 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114 }
Eric Laurentc722f302014-12-10 11:21:49 -08003115 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003116 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 if (res != NO_ERROR) {
3118 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003119 } else if (checkOutputs) {
3120 checkForDeviceAndOutputChanges();
3121 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003122 }
3123 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003124}
3125
3126status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3127{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003128 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003129 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003130 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003131 sp<HwModule> rSubmixModule;
3132 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003133 for (const auto& mix : mixes) {
3134 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003135
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003136 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003137 rSubmixModule = mHwModules.getModuleFromName(
3138 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3139 if (rSubmixModule == 0) {
3140 res = INVALID_OPERATION;
3141 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003142 }
3143 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003144
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003145 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003146
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003147 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003148 res = INVALID_OPERATION;
3149 continue;
3150 }
3151
Kevin Rocard04ed0462019-05-02 17:53:24 -07003152 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3153 if (getDeviceConnectionState(device, address.string()) ==
3154 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3155 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3156 address.string(), "remote-submix",
3157 AUDIO_FORMAT_DEFAULT);
3158 if (res != OK) {
3159 ALOGE("Error making RemoteSubmix device unavailable for mix "
3160 "with type %d, address %s", device, address.string());
3161 }
3162 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003163 }
jiabin5740f082019-08-19 15:08:30 -07003164 rSubmixModule->removeOutputProfile(address.c_str());
3165 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003166
Kevin Rocard153f92d2018-12-18 18:33:28 -08003167 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003168 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003169 res = INVALID_OPERATION;
3170 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003171 } else {
3172 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003173 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003174 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003175 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003176 if (res == NO_ERROR && checkOutputs) {
3177 checkForDeviceAndOutputChanges();
3178 updateCallAndOutputRouting();
3179 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003180 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003181}
3182
Mikhail Naganov100f0122018-11-29 11:22:16 -08003183void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3184{
3185 size_t i = 0;
3186 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3187 for (const auto& fmt : mManualSurroundFormats) {
3188 if (i++ != 0) dst->append(", ");
3189 std::string sfmt;
3190 FormatConverter::toString(fmt, sfmt);
3191 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3192 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3193 }
3194}
3195
Eric Laurentc529cf62020-04-17 18:19:10 -07003196// Returns true if all devices types match the predicate and are supported by one HW module
3197bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003198 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003199 std::function<bool(audio_devices_t)> predicate,
3200 const char *context) {
3201 for (size_t i = 0; i < devices.size(); i++) {
3202 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003203 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003204 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003205 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003206 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003207 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003208 return false;
3209 }
3210 }
3211 return true;
3212}
3213
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003214status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003215 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003216 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003217 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3218 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003219 }
3220 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003221 if (res != NO_ERROR) {
3222 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3223 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003224 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003225
3226 checkForDeviceAndOutputChanges();
3227 updateCallAndOutputRouting();
3228
3229 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003230}
3231
3232status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3233 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003234 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3235 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003236 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003237 __FUNCTION__, uid);
3238 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003239 }
3240
Eric Laurentc529cf62020-04-17 18:19:10 -07003241 checkForDeviceAndOutputChanges();
3242 updateCallAndOutputRouting();
3243
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003244 return res;
3245}
3246
Eric Laurent2517af32020-11-25 15:31:27 +01003247
jiabin0a488932020-08-07 17:32:40 -07003248status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3249 device_role_t role,
3250 const AudioDeviceTypeAddrVector &devices) {
3251 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3252 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003253
Eric Laurentc529cf62020-04-17 18:19:10 -07003254 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003255 return BAD_VALUE;
3256 }
jiabin0a488932020-08-07 17:32:40 -07003257 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003258 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003259 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3260 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003261 return status;
3262 }
3263
3264 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003265
3266 bool forceVolumeReeval = false;
3267 // FIXME: workaround for truncated touch sounds
3268 // to be removed when the problem is handled by system UI
3269 uint32_t delayMs = 0;
3270 if (strategy == mCommunnicationStrategy) {
3271 forceVolumeReeval = true;
3272 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3273 updateInputRouting();
3274 }
3275 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003276
3277 return NO_ERROR;
3278}
3279
3280void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3281{
3282 uint32_t waitMs = 0;
3283 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3284 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3285 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003286 // Only apply special touch sound delay once
3287 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003288 }
3289 for (size_t i = 0; i < mOutputs.size(); i++) {
3290 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3291 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3292 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3293 // As done in setDeviceConnectionState, we could also fix default device issue by
3294 // preventing the force re-routing in case of default dev that distinguishes on address.
3295 // Let's give back to engine full device choice decision however.
3296 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003297 // Only apply special touch sound delay once
3298 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003299 }
3300 if (forceVolumeReeval && !newDevices.isEmpty()) {
3301 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3302 }
3303 }
3304}
3305
Eric Laurent2517af32020-11-25 15:31:27 +01003306void AudioPolicyManager::updateInputRouting() {
3307 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3308 auto newDevice = getNewInputDevice(activeDesc);
3309 // Force new input selection if the new device can not be reached via current input
3310 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3311 setInputDevice(activeDesc->mIoHandle, newDevice);
3312 } else {
3313 closeInput(activeDesc->mIoHandle);
3314 }
3315 }
3316}
3317
jiabin0a488932020-08-07 17:32:40 -07003318status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3319 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003320{
jiabin0a488932020-08-07 17:32:40 -07003321 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003322
jiabin0a488932020-08-07 17:32:40 -07003323 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003324 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003325 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3326 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003327 return status;
3328 }
3329
3330 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003331
3332 bool forceVolumeReeval = false;
3333 // FIXME: workaround for truncated touch sounds
3334 // to be removed when the problem is handled by system UI
3335 uint32_t delayMs = 0;
3336 if (strategy == mCommunnicationStrategy) {
3337 forceVolumeReeval = true;
3338 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3339 updateInputRouting();
3340 }
3341 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003342
3343 return NO_ERROR;
3344}
3345
jiabin0a488932020-08-07 17:32:40 -07003346status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3347 device_role_t role,
3348 AudioDeviceTypeAddrVector &devices) {
3349 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003350}
3351
Jiabin Huang3b98d322020-09-03 17:54:16 +00003352status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3353 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3354 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3355 dumpAudioDeviceTypeAddrVector(devices).c_str());
3356
Mikhail Naganov55773032020-10-01 15:08:13 -07003357 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003358 return BAD_VALUE;
3359 }
3360 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3361 ALOGW_IF(status != NO_ERROR,
3362 "Engine could not set preferred devices %s for audio source %d role %d",
3363 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3364
3365 return status;
3366}
3367
3368status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3369 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3370 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3371 dumpAudioDeviceTypeAddrVector(devices).c_str());
3372
Mikhail Naganov55773032020-10-01 15:08:13 -07003373 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003374 return BAD_VALUE;
3375 }
3376 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3377 ALOGW_IF(status != NO_ERROR,
3378 "Engine could not add preferred devices %s for audio source %d role %d",
3379 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3380
Eric Laurent2517af32020-11-25 15:31:27 +01003381 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003382 return status;
3383}
3384
3385status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3386 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3387{
3388 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3389 dumpAudioDeviceTypeAddrVector(devices).c_str());
3390
Mikhail Naganov55773032020-10-01 15:08:13 -07003391 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003392 return BAD_VALUE;
3393 }
3394
3395 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3396 audioSource, role, devices);
3397 ALOGW_IF(status != NO_ERROR,
3398 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3399
Eric Laurent2517af32020-11-25 15:31:27 +01003400 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003401 return status;
3402}
3403
3404status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3405 device_role_t role) {
3406 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3407
3408 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3409 ALOGW_IF(status != NO_ERROR,
3410 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3411
Eric Laurent2517af32020-11-25 15:31:27 +01003412 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003413 return status;
3414}
3415
3416status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3417 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3418 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3419}
3420
Oscar Azucena90e77632019-11-27 17:12:28 -08003421status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003422 const AudioDeviceTypeAddrVector& devices) {
3423 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003424 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3425 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003426 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003427 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3428 if (status != NO_ERROR) {
3429 ALOGE("%s() could not set device affinity for userId %d",
3430 __FUNCTION__, userId);
3431 return status;
3432 }
3433
3434 // reevaluate outputs for all devices
3435 checkForDeviceAndOutputChanges();
3436 updateCallAndOutputRouting();
3437
3438 return NO_ERROR;
3439}
3440
3441status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3442 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3443 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3444 if (status != NO_ERROR) {
3445 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3446 __FUNCTION__, userId);
3447 return status;
3448 }
3449
3450 // reevaluate outputs for all devices
3451 checkForDeviceAndOutputChanges();
3452 updateCallAndOutputRouting();
3453
3454 return NO_ERROR;
3455}
3456
Andy Hungc29d82b2018-10-05 12:23:17 -07003457void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003458{
Andy Hungc29d82b2018-10-05 12:23:17 -07003459 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3460 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003461 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003462 std::string stateLiteral;
3463 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003464 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003465 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3466 "communications", "media", "record", "dock", "system",
3467 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3468 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3469 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003470 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3471 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3472 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3473 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3474 dst->append(" (MANUAL: ");
3475 dumpManualSurroundFormats(dst);
3476 dst->append(")");
3477 }
3478 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003479 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003480 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3481 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003482 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003483 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003484
Andy Hungc29d82b2018-10-05 12:23:17 -07003485 mAvailableOutputDevices.dump(dst, String8("Available output"));
3486 mAvailableInputDevices.dump(dst, String8("Available input"));
3487 mHwModulesAll.dump(dst);
3488 mOutputs.dump(dst);
3489 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003490 mEffects.dump(dst);
3491 mAudioPatches.dump(dst);
3492 mPolicyMixes.dump(dst);
3493 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003494
Kevin Rocardb99cc752019-03-21 20:52:24 -07003495 dst->appendFormat(" AllowedCapturePolicies:\n");
3496 for (auto& policy : mAllowedCapturePolicies) {
3497 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3498 }
3499
François Gaffiec005e562018-11-06 15:04:49 +01003500 dst->appendFormat("\nPolicy Engine dump:\n");
3501 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003502}
3503
3504status_t AudioPolicyManager::dump(int fd)
3505{
3506 String8 result;
3507 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003508 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003509 return NO_ERROR;
3510}
3511
Kevin Rocardb99cc752019-03-21 20:52:24 -07003512status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3513{
3514 mAllowedCapturePolicies[uid] = capturePolicy;
3515 return NO_ERROR;
3516}
3517
Eric Laurente552edb2014-03-10 17:42:56 -07003518// This function checks for the parameters which can be offloaded.
3519// This can be enhanced depending on the capability of the DSP and policy
3520// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003521audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003522{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003523 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003524 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003525 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003526 offloadInfo.format,
3527 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3528 offloadInfo.has_video);
3529
Andy Hung2ddee192015-12-18 17:34:44 -08003530 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003531 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003532 }
3533
Eric Laurente552edb2014-03-10 17:42:56 -07003534 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003535 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003536 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3537 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 }
3539
3540 // Check if stream type is music, then only allow offload as of now.
3541 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3542 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003543 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3544 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003545 }
3546
3547 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003548 const bool allowOffloadWithVideo =
3549 property_get_bool("audio.offload.video", false /* default_value */);
3550 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003551 ALOGV("%s: has_video == true, returning false", __func__);
3552 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003553 }
3554
3555 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003556 const int min_duration_secs = property_get_int32(
3557 "audio.offload.min.duration.secs", -1 /* default_value */);
3558 if (min_duration_secs >= 0) {
3559 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003560 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3561 __func__, min_duration_secs);
3562 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003563 }
3564 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003565 ALOGV("%s: Offload denied by duration < default min(=%u)",
3566 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3567 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003568 }
3569
3570 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3571 // creating an offloaded track and tearing it down immediately after start when audioflinger
3572 // detects there is an active non offloadable effect.
3573 // FIXME: We should check the audio session here but we do not have it in this context.
3574 // This may prevent offloading in rare situations where effects are left active by apps
3575 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003576 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003577 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003578 }
3579
3580 // See if there is a profile to support this.
3581 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003582 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003583 offloadInfo.sample_rate,
3584 offloadInfo.format,
3585 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003586 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3587 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003588 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3589 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3590 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003591 if (profile == nullptr) {
3592 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3593 }
3594 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3595 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3596 }
3597 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003598}
3599
Michael Chana94fbb22018-04-24 14:31:19 +10003600bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3601 const audio_attributes_t& attributes) {
3602 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003603 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003604 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003605 config.sample_rate,
3606 config.format,
3607 config.channel_mask,
3608 output_flags,
3609 true /* directOnly */);
3610 ALOGV("%s() profile %sfound with name: %s, "
3611 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3612 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003613 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003614 config.sample_rate, config.format, config.channel_mask, output_flags);
3615 return (profile != 0);
3616}
3617
Eric Laurent6a94d692014-05-20 11:18:06 -07003618status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3619 audio_port_type_t type,
3620 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003621 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003622 unsigned int *generation)
3623{
jiabin19cdba52020-11-24 11:28:58 -08003624 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3625 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003626 return BAD_VALUE;
3627 }
3628 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003629 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003630 *num_ports = 0;
3631 }
3632
3633 size_t portsWritten = 0;
3634 size_t portsMax = *num_ports;
3635 *num_ports = 0;
3636 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003637 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3638 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003639 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003640 for (const auto& dev : mAvailableOutputDevices) {
3641 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003642 continue;
3643 }
3644 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003645 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003646 }
3647 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003648 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003649 }
3650 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003651 for (const auto& dev : mAvailableInputDevices) {
3652 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003653 continue;
3654 }
3655 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003656 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003657 }
3658 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003659 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003660 }
3661 }
3662 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3663 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3664 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3665 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3666 }
3667 *num_ports += mInputs.size();
3668 }
3669 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003670 size_t numOutputs = 0;
3671 for (size_t i = 0; i < mOutputs.size(); i++) {
3672 if (!mOutputs[i]->isDuplicated()) {
3673 numOutputs++;
3674 if (portsWritten < portsMax) {
3675 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3676 }
3677 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003678 }
Eric Laurent84c70242014-06-23 08:46:27 -07003679 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003680 }
3681 }
3682 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003683 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003684 return NO_ERROR;
3685}
3686
jiabin19cdba52020-11-24 11:28:58 -08003687status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003688{
Eric Laurent99fcae42018-05-17 16:59:18 -07003689 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3690 return BAD_VALUE;
3691 }
3692 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3693 if (dev != 0) {
3694 dev->toAudioPort(port);
3695 return NO_ERROR;
3696 }
3697 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3698 if (dev != 0) {
3699 dev->toAudioPort(port);
3700 return NO_ERROR;
3701 }
3702 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3703 if (out != 0) {
3704 out->toAudioPort(port);
3705 return NO_ERROR;
3706 }
3707 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3708 if (in != 0) {
3709 in->toAudioPort(port);
3710 return NO_ERROR;
3711 }
3712 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003713}
3714
François Gaffieafd4cea2019-11-18 15:50:22 +01003715status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3716 audio_patch_handle_t *handle,
3717 uid_t uid, uint32_t delayMs,
3718 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003719{
François Gaffieafd4cea2019-11-18 15:50:22 +01003720 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 if (handle == NULL || patch == NULL) {
3722 return BAD_VALUE;
3723 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003724 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003725
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003726 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003727 return BAD_VALUE;
3728 }
3729 // only one source per audio patch supported for now
3730 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 return INVALID_OPERATION;
3732 }
Eric Laurent874c42872014-08-08 15:13:39 -07003733
3734 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003735 return INVALID_OPERATION;
3736 }
Eric Laurent874c42872014-08-08 15:13:39 -07003737 for (size_t i = 0; i < patch->num_sinks; i++) {
3738 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3739 return INVALID_OPERATION;
3740 }
3741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003742
3743 sp<AudioPatch> patchDesc;
3744 ssize_t index = mAudioPatches.indexOfKey(*handle);
3745
François Gaffieafd4cea2019-11-18 15:50:22 +01003746 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3747 patch->sources[0].role,
3748 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003749#if LOG_NDEBUG == 0
3750 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003751 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3752 patch->sinks[i].role,
3753 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003754 }
3755#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003756
3757 if (index >= 0) {
3758 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003759 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3760 __func__, mUidCached, patchDesc->getUid(), uid);
3761 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003762 return INVALID_OPERATION;
3763 }
3764 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003765 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003766 }
3767
3768 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003769 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003771 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003772 return BAD_VALUE;
3773 }
Eric Laurent84c70242014-06-23 08:46:27 -07003774 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3775 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003776 if (patchDesc != 0) {
3777 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003778 ALOGV("%s source id differs for patch current id %d new id %d",
3779 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003780 return BAD_VALUE;
3781 }
3782 }
Eric Laurent874c42872014-08-08 15:13:39 -07003783 DeviceVector devices;
3784 for (size_t i = 0; i < patch->num_sinks; i++) {
3785 // Only support mix to devices connection
3786 // TODO add support for mix to mix connection
3787 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003788 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003789 return INVALID_OPERATION;
3790 }
3791 sp<DeviceDescriptor> devDesc =
3792 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3793 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003794 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003795 return BAD_VALUE;
3796 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003797
François Gaffie11d30102018-11-02 16:09:09 +01003798 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003799 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003800 NULL, // updatedSamplingRate
3801 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003802 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003803 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003804 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003805 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003806 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003807 return INVALID_OPERATION;
3808 }
3809 devices.add(devDesc);
3810 }
3811 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003812 return INVALID_OPERATION;
3813 }
Eric Laurent874c42872014-08-08 15:13:39 -07003814
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003816 ALOGV("%s setting device %s on output %d",
3817 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003818 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003819 index = mAudioPatches.indexOfKey(*handle);
3820 if (index >= 0) {
3821 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003822 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 }
3824 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003825 patchDesc->setUid(uid);
3826 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003827 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003828 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003829 return INVALID_OPERATION;
3830 }
3831 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3832 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3833 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003834 // only one sink supported when connecting an input device to a mix
3835 if (patch->num_sinks > 1) {
3836 return INVALID_OPERATION;
3837 }
François Gaffie53615e22015-03-19 09:24:12 +01003838 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003839 if (inputDesc == NULL) {
3840 return BAD_VALUE;
3841 }
3842 if (patchDesc != 0) {
3843 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3844 return BAD_VALUE;
3845 }
3846 }
François Gaffie11d30102018-11-02 16:09:09 +01003847 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003849 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003850 return BAD_VALUE;
3851 }
3852
François Gaffie11d30102018-11-02 16:09:09 +01003853 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003854 patch->sinks[0].sample_rate,
3855 NULL, /*updatedSampleRate*/
3856 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003857 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003858 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003859 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003860 // FIXME for the parameter type,
3861 // and the NONE
3862 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003863 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 return INVALID_OPERATION;
3865 }
3866 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003867 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003868 device->toString().c_str(), inputDesc->mIoHandle);
3869 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 index = mAudioPatches.indexOfKey(*handle);
3871 if (index >= 0) {
3872 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003873 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003874 }
3875 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003876 patchDesc->setUid(uid);
3877 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003878 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003879 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003880 return INVALID_OPERATION;
3881 }
3882 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3883 // device to device connection
3884 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003885 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003886 return BAD_VALUE;
3887 }
3888 }
François Gaffie11d30102018-11-02 16:09:09 +01003889 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003890 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003891 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003892 return BAD_VALUE;
3893 }
Eric Laurent874c42872014-08-08 15:13:39 -07003894
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 //update source and sink with our own data as the data passed in the patch may
3896 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003897 PatchBuilder patchBuilder;
3898 audio_port_config sourcePortConfig = {};
3899 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3900 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003901
Eric Laurent874c42872014-08-08 15:13:39 -07003902 for (size_t i = 0; i < patch->num_sinks; i++) {
3903 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003904 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003905 return INVALID_OPERATION;
3906 }
François Gaffie11d30102018-11-02 16:09:09 +01003907 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003908 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003909 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003910 return BAD_VALUE;
3911 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003912 audio_port_config sinkPortConfig = {};
3913 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3914 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003915
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003916 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3917 // volume management purpose (tracking activity)
3918 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
3919 // in config XML to reach the sink so that is can be declared as available.
3920 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3921 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
3922 if (sourceDesc != nullptr) {
3923 // take care of dynamic routing for SwOutput selection,
3924 audio_attributes_t attributes = sourceDesc->attributes();
3925 audio_stream_type_t stream = sourceDesc->stream();
3926 audio_attributes_t resultAttr;
3927 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3928 config.sample_rate = sourceDesc->config().sample_rate;
3929 config.channel_mask = sourceDesc->config().channel_mask;
3930 config.format = sourceDesc->config().format;
3931 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3932 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3933 bool isRequestedDeviceForExclusiveUse = false;
3934 output_type_t outputType;
3935 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3936 &stream, sourceDesc->uid(), &config, &flags,
3937 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3938 nullptr, &outputType);
3939 if (output == AUDIO_IO_HANDLE_NONE) {
3940 ALOGV("%s no output for device %s",
3941 __FUNCTION__, sinkDevice->toString().c_str());
3942 return INVALID_OPERATION;
3943 }
3944 outputDesc = mOutputs.valueFor(output);
3945 if (outputDesc->isDuplicated()) {
3946 ALOGE("%s output is duplicated", __func__);
3947 return INVALID_OPERATION;
3948 }
3949 sourceDesc->setSwOutput(outputDesc);
3950 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07003951 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003952 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003953 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003954 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003955 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3956 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003957 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3958 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003959 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3960 (sourceDesc != nullptr &&
3961 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003962 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003963 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003964 return INVALID_OPERATION;
3965 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003966 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003967 SortedVector<audio_io_handle_t> outputs =
3968 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3969 // if the sink device is reachable via an opened output stream, request to
3970 // go via this output stream by adding a second source to the patch
3971 // description
3972 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003973 if (output != AUDIO_IO_HANDLE_NONE) {
3974 outputDesc = mOutputs.valueFor(output);
3975 if (outputDesc->isDuplicated()) {
3976 ALOGV("%s output for device %s is duplicated",
3977 __FUNCTION__, sinkDevice->toString().c_str());
3978 return INVALID_OPERATION;
3979 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003980 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003981 }
3982 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003983 audio_port_config srcMixPortConfig = {};
3984 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01003985 // for volume control, we may need a valid stream
3986 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3987 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3988 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003989 }
Eric Laurent83b88082014-06-20 18:31:16 -07003990 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 }
3992 // TODO: check from routing capabilities in config file and other conflicting patches
3993
François Gaffieafd4cea2019-11-18 15:50:22 +01003994 status_t status = installPatch(
3995 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003996 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003997 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003998 return INVALID_OPERATION;
3999 }
4000 } else {
4001 return BAD_VALUE;
4002 }
4003 } else {
4004 return BAD_VALUE;
4005 }
4006 return NO_ERROR;
4007}
4008
4009status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4010 uid_t uid)
4011{
4012 ALOGV("releaseAudioPatch() patch %d", handle);
4013
4014 ssize_t index = mAudioPatches.indexOfKey(handle);
4015
4016 if (index < 0) {
4017 return BAD_VALUE;
4018 }
4019 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004020 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4021 __func__, mUidCached, patchDesc->getUid(), uid);
4022 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004023 return INVALID_OPERATION;
4024 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004025 return releaseAudioPatchInternal(handle);
4026}
Eric Laurent6a94d692014-05-20 11:18:06 -07004027
François Gaffieafd4cea2019-11-18 15:50:22 +01004028status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4029 uint32_t delayMs)
4030{
4031 ALOGV("%s patch %d", __func__, handle);
4032 if (mAudioPatches.indexOfKey(handle) < 0) {
4033 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4034 return BAD_VALUE;
4035 }
4036 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004037 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004038 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004039 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004040 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004041 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004042 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004043 return BAD_VALUE;
4044 }
4045
François Gaffie11d30102018-11-02 16:09:09 +01004046 setOutputDevices(outputDesc,
4047 getNewOutputDevices(outputDesc, true /*fromCache*/),
4048 true,
4049 0,
4050 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004051 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4052 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004053 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004054 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004055 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004056 return BAD_VALUE;
4057 }
4058 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004059 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004060 true,
4061 NULL);
4062 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004063 status_t status =
4064 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4065 ALOGV("%s patch panel returned %d patchHandle %d",
4066 __func__, status, patchDesc->getAfHandle());
4067 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004068 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004069 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004070 // SW Bridge
4071 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4072 sp<SwAudioOutputDescriptor> outputDesc =
4073 mOutputs.getOutputFromId(patch->sources[1].id);
4074 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004075 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4076 // releaseOutput has already called closeOuput in case of direct output
4077 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004078 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004079 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4080 // force SwOutput patch removal as AF counter part patch has already gone.
4081 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4082 removeAudioPatch(outputDesc->getPatchHandle());
4083 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004084 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4085 setOutputDevices(outputDesc,
4086 getNewOutputDevices(outputDesc, true /*fromCache*/),
4087 true, /*force*/
4088 0,
4089 NULL);
4090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 } else {
4092 return BAD_VALUE;
4093 }
4094 } else {
4095 return BAD_VALUE;
4096 }
4097 return NO_ERROR;
4098}
4099
4100status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4101 struct audio_patch *patches,
4102 unsigned int *generation)
4103{
François Gaffie53615e22015-03-19 09:24:12 +01004104 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 return BAD_VALUE;
4106 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004107 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004108 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004109}
4110
Eric Laurente1715a42014-05-20 11:30:42 -07004111status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004112{
Eric Laurente1715a42014-05-20 11:30:42 -07004113 ALOGV("setAudioPortConfig()");
4114
4115 if (config == NULL) {
4116 return BAD_VALUE;
4117 }
4118 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4119 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004120 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4121 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004122 }
4123
Eric Laurenta121f902014-06-03 13:32:54 -07004124 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004125 if (config->type == AUDIO_PORT_TYPE_MIX) {
4126 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004127 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004128 if (outputDesc == NULL) {
4129 return BAD_VALUE;
4130 }
Eric Laurent84c70242014-06-23 08:46:27 -07004131 ALOG_ASSERT(!outputDesc->isDuplicated(),
4132 "setAudioPortConfig() called on duplicated output %d",
4133 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004134 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004135 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004136 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004137 if (inputDesc == NULL) {
4138 return BAD_VALUE;
4139 }
Eric Laurenta121f902014-06-03 13:32:54 -07004140 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004141 } else {
4142 return BAD_VALUE;
4143 }
4144 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4145 sp<DeviceDescriptor> deviceDesc;
4146 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4147 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4148 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4149 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4150 } else {
4151 return BAD_VALUE;
4152 }
4153 if (deviceDesc == NULL) {
4154 return BAD_VALUE;
4155 }
Eric Laurenta121f902014-06-03 13:32:54 -07004156 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004157 } else {
4158 return BAD_VALUE;
4159 }
4160
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004161 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004162 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4163 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004164 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004165 audioPortConfig->toAudioPortConfig(&newConfig, config);
4166 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004167 }
Eric Laurenta121f902014-06-03 13:32:54 -07004168 if (status != NO_ERROR) {
4169 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004170 }
Eric Laurente1715a42014-05-20 11:30:42 -07004171
4172 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004173}
4174
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004175void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4176{
Eric Laurentd60560a2015-04-10 11:31:20 -07004177 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004178 clearAudioPatches(uid);
4179 clearSessionRoutes(uid);
4180}
4181
Eric Laurent6a94d692014-05-20 11:18:06 -07004182void AudioPolicyManager::clearAudioPatches(uid_t uid)
4183{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004184 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004186 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004187 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 }
4189 }
4190}
4191
François Gaffiec005e562018-11-06 15:04:49 +01004192void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004193{
François Gaffiec005e562018-11-06 15:04:49 +01004194 // Take the first attributes following the product strategy as it is used to retrieve the routed
4195 // device. All attributes wihin a strategy follows the same "routing strategy"
4196 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4197 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004198 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004199 for (size_t j = 0; j < mOutputs.size(); j++) {
4200 if (mOutputs.keyAt(j) == ouptutToSkip) {
4201 continue;
4202 }
4203 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004204 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004205 continue;
4206 }
4207 // If the default device for this strategy is on another output mix,
4208 // invalidate all tracks in this strategy to force re connection.
4209 // Otherwise select new device on the output mix.
4210 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004211 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4212 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004213 }
4214 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004215 setOutputDevices(
4216 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004217 }
4218 }
4219}
4220
4221void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4222{
4223 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004224 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004225 for (size_t i = 0; i < mOutputs.size(); i++) {
4226 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004227 for (const auto& client : outputDesc->getClientIterable()) {
4228 if (client->hasPreferredDevice() && client->uid() == uid) {
4229 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004230 auto clientStrategy = client->strategy();
4231 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4232 end(affectedStrategies)) {
4233 continue;
4234 }
4235 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004236 }
4237 }
4238 }
4239 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004240 for (const auto& strategy : affectedStrategies) {
4241 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004242 }
4243
4244 // remove input routes associated with this uid
4245 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004246 for (size_t i = 0; i < mInputs.size(); i++) {
4247 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004248 for (const auto& client : inputDesc->getClientIterable()) {
4249 if (client->hasPreferredDevice() && client->uid() == uid) {
4250 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4251 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004252 }
4253 }
4254 }
4255 // reroute inputs if necessary
4256 SortedVector<audio_io_handle_t> inputsToClose;
4257 for (size_t i = 0; i < mInputs.size(); i++) {
4258 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004259 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004260 inputsToClose.add(inputDesc->mIoHandle);
4261 }
4262 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004263 for (const auto& input : inputsToClose) {
4264 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004265 }
4266}
4267
Eric Laurentd60560a2015-04-10 11:31:20 -07004268void AudioPolicyManager::clearAudioSources(uid_t uid)
4269{
4270 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004271 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4272 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004273 stopAudioSource(mAudioSources.keyAt(i));
4274 }
4275 }
4276}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004277
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004278status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4279 audio_io_handle_t *ioHandle,
4280 audio_devices_t *device)
4281{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004282 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4283 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004284 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004285 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004286
François Gaffiedf372692015-03-19 10:43:27 +01004287 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004288}
4289
Eric Laurentd60560a2015-04-10 11:31:20 -07004290status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004291 const audio_attributes_t *attributes,
4292 audio_port_handle_t *portId,
4293 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004294{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004295 ALOGV("%s", __FUNCTION__);
4296 *portId = AUDIO_PORT_HANDLE_NONE;
4297
4298 if (source == NULL || attributes == NULL || portId == NULL) {
4299 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4300 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004301 return BAD_VALUE;
4302 }
4303
Eric Laurentd60560a2015-04-10 11:31:20 -07004304 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4305 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004306 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4307 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004308 return INVALID_OPERATION;
4309 }
4310
François Gaffie11d30102018-11-02 16:09:09 +01004311 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004312 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004313 String8(source->ext.device.address),
4314 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004315 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004316 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004317 return BAD_VALUE;
4318 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004319
jiabin4ef93452019-09-10 14:29:54 -07004320 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004321
François Gaffieaaac0fd2018-11-22 17:56:39 +01004322 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004323 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004324 mEngine->getStreamTypeForAttributes(*attributes),
4325 mEngine->getProductStrategyForAttributes(*attributes),
4326 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004327
4328 status_t status = connectAudioSource(sourceDesc);
4329 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004330 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004331 }
4332 return status;
4333}
4334
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004335status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004336{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004337 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004338
4339 // make sure we only have one patch per source.
4340 disconnectAudioSource(sourceDesc);
4341
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004342 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004343 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4344 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4345 sourceDesc->srcDevice()->type(),
4346 String8(sourceDesc->srcDevice()->address().c_str()),
4347 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004348 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004349 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004350 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004351 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004352 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4353 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4354 return INVALID_OPERATION;
4355 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004356 PatchBuilder patchBuilder;
4357 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4358 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4359 status_t status =
4360 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4361 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4362 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4363 return INVALID_OPERATION;
4364 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004365 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004366 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4367 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4368 if (swOutput != 0) {
4369 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004370 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004371 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004372 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004373 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004374 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004375 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004376 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004377 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004378 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004379 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004380 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004381 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4382 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004383 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004384 if (delayMs != 0) {
4385 usleep(delayMs * 1000);
4386 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004387 } else {
4388 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4389 if (hwOutputDesc != 0) {
4390 // create Hwoutput and add to mHwOutputs
4391 } else {
4392 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4393 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004394 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004395 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004396
4397FailureSourceActive:
4398 swOutput->stop();
4399 releaseOutput(sourceDesc->portId());
4400FailureSourceAdded:
4401 sourceDesc->setSwOutput(nullptr);
4402FailureReleasePatch:
4403 releaseAudioPatchInternal(handle);
4404 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004405}
4406
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004407status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004408{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004409 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4410 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004411 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004412 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004413 return BAD_VALUE;
4414 }
4415 status_t status = disconnectAudioSource(sourceDesc);
4416
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004417 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004418 return status;
4419}
4420
Andy Hung2ddee192015-12-18 17:34:44 -08004421status_t AudioPolicyManager::setMasterMono(bool mono)
4422{
4423 if (mMasterMono == mono) {
4424 return NO_ERROR;
4425 }
4426 mMasterMono = mono;
4427 // if enabling mono we close all offloaded devices, which will invalidate the
4428 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4429 // for recreating the new AudioTrack as non-offloaded PCM.
4430 //
4431 // If disabling mono, we leave all tracks as is: we don't know which clients
4432 // and tracks are able to be recreated as offloaded. The next "song" should
4433 // play back offloaded.
4434 if (mMasterMono) {
4435 Vector<audio_io_handle_t> offloaded;
4436 for (size_t i = 0; i < mOutputs.size(); ++i) {
4437 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4438 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4439 offloaded.push(desc->mIoHandle);
4440 }
4441 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004442 for (const auto& handle : offloaded) {
4443 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004444 }
4445 }
4446 // update master mono for all remaining outputs
4447 for (size_t i = 0; i < mOutputs.size(); ++i) {
4448 updateMono(mOutputs.keyAt(i));
4449 }
4450 return NO_ERROR;
4451}
4452
4453status_t AudioPolicyManager::getMasterMono(bool *mono)
4454{
4455 *mono = mMasterMono;
4456 return NO_ERROR;
4457}
4458
Eric Laurentac9cef52017-06-09 15:46:26 -07004459float AudioPolicyManager::getStreamVolumeDB(
4460 audio_stream_type_t stream, int index, audio_devices_t device)
4461{
jiabin9a3361e2019-10-01 09:38:30 -07004462 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004463}
4464
jiabin81772902018-04-02 17:52:27 -07004465status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4466 audio_format_t *surroundFormats,
4467 bool *surroundFormatsEnabled,
4468 bool reported)
4469{
4470 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4471 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4472 return BAD_VALUE;
4473 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004474 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4475 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004476
4477 size_t formatsWritten = 0;
4478 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004479 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004480 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004481 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004482 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004483 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4484 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004485 audio_devices_t deviceType = device->type();
4486 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4487 // returns formats reported by HDMI devices.
4488 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4489 continue;
4490 }
4491 // Formats reported by sink devices
4492 std::unordered_set<audio_format_t> formatset;
4493 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4494 formatset.insert(it->second.begin(), it->second.end());
4495 }
4496
4497 // Formats hard-coded in the in policy configuration file (if any).
4498 FormatVector encodedFormats = device->encodedFormats();
4499 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4500 // Filter the formats which are supported by the vendor hardware.
4501 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4502 if (mConfig.getSurroundFormats().count(*it) != 0) {
4503 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004504 } else {
4505 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004506 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004507 formats.insert(pair.first);
4508 break;
4509 }
4510 }
4511 }
4512 }
jiabin81772902018-04-02 17:52:27 -07004513 }
4514 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004515 for (const auto& pair : mConfig.getSurroundFormats()) {
4516 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004517 }
4518 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004519 *numSurroundFormats = formats.size();
4520 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4521 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004522 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004523 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004524 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004525 bool formatEnabled = true;
4526 switch (forceUse) {
4527 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4528 formatEnabled = mManualSurroundFormats.count(format) != 0;
4529 break;
4530 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4531 formatEnabled = false;
4532 break;
4533 default: // AUTO or ALWAYS => true
4534 break;
jiabin81772902018-04-02 17:52:27 -07004535 }
4536 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4537 }
jiabin81772902018-04-02 17:52:27 -07004538 }
4539 return NO_ERROR;
4540}
4541
4542status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4543{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004544 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004545 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4546 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004547 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004548 return BAD_VALUE;
4549 }
4550
Mikhail Naganov100f0122018-11-29 11:22:16 -08004551 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4552 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004553 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004554 return INVALID_OPERATION;
4555 }
4556
Mikhail Naganov100f0122018-11-29 11:22:16 -08004557 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004558 return NO_ERROR;
4559 }
4560
Mikhail Naganov100f0122018-11-29 11:22:16 -08004561 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004562 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004563 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004564 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004565 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004566 }
4567 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004568 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004569 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004570 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004571 }
4572 }
4573
4574 sp<SwAudioOutputDescriptor> outputDesc;
4575 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004576 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4577 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004578 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4579 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004580 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004581 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004582 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4583 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4584 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004585 name.c_str(),
4586 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004587 if (status != NO_ERROR) {
4588 continue;
4589 }
4590 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4591 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4592 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004593 name.c_str(),
4594 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004595 profileUpdated |= (status == NO_ERROR);
4596 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004597 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004598 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004599 AUDIO_DEVICE_IN_HDMI);
4600 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4601 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004602 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004603 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004604 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4605 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4606 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004607 name.c_str(),
4608 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004609 if (status != NO_ERROR) {
4610 continue;
4611 }
4612 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4614 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004615 name.c_str(),
4616 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004617 profileUpdated |= (status == NO_ERROR);
4618 }
4619
jiabin81772902018-04-02 17:52:27 -07004620 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004621 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004622 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004623 }
4624
4625 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4626}
4627
Eric Laurent5ada82e2019-08-29 17:53:54 -07004628void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004629{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004630 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004631 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004632 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004633 }
4634}
4635
jiabin6012f912018-11-02 17:06:30 -07004636bool AudioPolicyManager::isHapticPlaybackSupported()
4637{
4638 for (const auto& hwModule : mHwModules) {
4639 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4640 for (const auto &outProfile : outputProfiles) {
4641 struct audio_port audioPort;
4642 outProfile->toAudioPort(&audioPort);
4643 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4644 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4645 return true;
4646 }
4647 }
4648 }
4649 }
4650 return false;
4651}
4652
Eric Laurent8340e672019-11-06 11:01:08 -08004653bool AudioPolicyManager::isCallScreenModeSupported()
4654{
4655 return getConfig().isCallScreenModeSupported();
4656}
4657
4658
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004659status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004660{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004661 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004662 if (!sourceDesc->isConnected()) {
4663 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4664 return NO_ERROR;
4665 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004666 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4667 if (swOutput != 0) {
4668 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004669 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004671 }
jiabinbce0c1d2020-10-05 11:20:18 -07004672 if (releaseOutput(sourceDesc->portId())) {
4673 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4674 // no need to release audio patch here but just return NO_ERROR.
4675 return NO_ERROR;
4676 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004677 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004678 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004679 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004680 // close Hwoutput and remove from mHwOutputs
4681 } else {
4682 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4683 }
4684 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004685 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4686 sourceDesc->disconnect();
4687 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004688}
4689
François Gaffiec005e562018-11-06 15:04:49 +01004690sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4691 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004692{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004693 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004694 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004695 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004696 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004697 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4698 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004699 source = sourceDesc;
4700 break;
4701 }
4702 }
4703 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004704}
4705
Eric Laurente552edb2014-03-10 17:42:56 -07004706// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004707// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004708// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004709uint32_t AudioPolicyManager::nextAudioPortGeneration()
4710{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004711 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004712}
4713
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004714static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004715 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4716 !audioPolicyXmlConfigFile.empty()) {
4717 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4718 if (ret == NO_ERROR) {
4719 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004720 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004721 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004722 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004723 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004724}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004725
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004726AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4727 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004728 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004729 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004730 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004731 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004732 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004733 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004734 mAudioPortGeneration(1),
4735 mBeaconMuteRefCount(0),
4736 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004737 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004738 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004739 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004740 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004741{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004742}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004743
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004744AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4745 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4746{
4747 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004748}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004749
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004750void AudioPolicyManager::loadConfig() {
4751 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004752 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004753 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004754 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004755}
4756
4757status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004758 {
4759 auto engLib = EngineLibrary::load(
4760 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4761 if (!engLib) {
4762 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4763 return NO_INIT;
4764 }
4765 mEngine = engLib->createEngine();
4766 if (mEngine == nullptr) {
4767 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4768 return NO_INIT;
4769 }
François Gaffie2110e042015-03-24 08:41:51 +01004770 }
4771 mEngine->setObserver(this);
4772 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004773 if (status != NO_ERROR) {
4774 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4775 return status;
4776 }
François Gaffie2110e042015-03-24 08:41:51 +01004777
Eric Laurent1d69c872021-01-11 18:53:01 +01004778 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4779 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4780
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004781 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004782 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004783 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004784
Eric Laurent3a4311c2014-03-17 12:00:47 -07004785 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004786 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4787 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4788 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004789 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004790 }
jiabin9ff780e2018-03-19 18:19:52 -07004791 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004792 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004793 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004794 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004795 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004796 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004797 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004798 }
4799 }
4800 }
Eric Laurente552edb2014-03-10 17:42:56 -07004801
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004802 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004803
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004804 // Silence ALOGV statements
4805 property_set("log.tag." LOG_TAG, "D");
4806
Eric Laurente552edb2014-03-10 17:42:56 -07004807 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004808 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004809}
4810
Eric Laurente0720872014-03-11 09:30:41 -07004811AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004812{
Eric Laurente552edb2014-03-10 17:42:56 -07004813 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004814 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004815 }
4816 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004817 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004818 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004819 mAvailableOutputDevices.clear();
4820 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004821 mOutputs.clear();
4822 mInputs.clear();
4823 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004824 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004825 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004826}
4827
Eric Laurente0720872014-03-11 09:30:41 -07004828status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004829{
Eric Laurent87ffa392015-05-22 10:32:38 -07004830 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004831}
4832
Eric Laurente552edb2014-03-10 17:42:56 -07004833// ---
4834
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004835void AudioPolicyManager::onNewAudioModulesAvailable()
4836{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004837 DeviceVector newDevices;
4838 onNewAudioModulesAvailableInt(&newDevices);
4839 if (!newDevices.empty()) {
4840 nextAudioPortGeneration();
4841 mpClientInterface->onAudioPortListUpdate();
4842 }
4843}
4844
4845void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4846{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004847 for (const auto& hwModule : mHwModulesAll) {
4848 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4849 continue;
4850 }
4851 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4852 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4853 ALOGW("could not open HW module %s", hwModule->getName());
4854 continue;
4855 }
4856 mHwModules.push_back(hwModule);
4857 // open all output streams needed to access attached devices
4858 // except for direct output streams that are only opened when they are actually
4859 // required by an app.
4860 // This also validates mAvailableOutputDevices list
4861 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4862 if (!outProfile->canOpenNewIo()) {
4863 ALOGE("Invalid Output profile max open count %u for profile %s",
4864 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4865 continue;
4866 }
4867 if (!outProfile->hasSupportedDevices()) {
4868 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4869 continue;
4870 }
4871 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4872 mTtsOutputAvailable = true;
4873 }
4874
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004875 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4876 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4877 sp<DeviceDescriptor> supportedDevice = 0;
4878 if (supportedDevices.contains(mDefaultOutputDevice)) {
4879 supportedDevice = mDefaultOutputDevice;
4880 } else {
4881 // choose first device present in profile's SupportedDevices also part of
4882 // mAvailableOutputDevices.
4883 if (availProfileDevices.isEmpty()) {
4884 continue;
4885 }
4886 supportedDevice = availProfileDevices.itemAt(0);
4887 }
4888 if (!mOutputDevicesAll.contains(supportedDevice)) {
4889 continue;
4890 }
4891 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4892 mpClientInterface);
4893 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4894 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4895 AUDIO_STREAM_DEFAULT,
4896 AUDIO_OUTPUT_FLAG_NONE, &output);
4897 if (status != NO_ERROR) {
4898 ALOGW("Cannot open output stream for devices %s on hw module %s",
4899 supportedDevice->toString().c_str(), hwModule->getName());
4900 continue;
4901 }
4902 for (const auto &device : availProfileDevices) {
4903 // give a valid ID to an attached device once confirmed it is reachable
4904 if (!device->isAttached()) {
4905 device->attach(hwModule);
4906 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004907 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004908 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004909 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4910 }
4911 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004912 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004913 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4914 mPrimaryOutput = outputDesc;
4915 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004916 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4917 outputDesc->close();
4918 } else {
4919 addOutput(output, outputDesc);
4920 setOutputDevices(outputDesc,
4921 DeviceVector(supportedDevice),
4922 true,
4923 0,
4924 NULL);
4925 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004926 }
4927 // open input streams needed to access attached devices to validate
4928 // mAvailableInputDevices list
4929 for (const auto& inProfile : hwModule->getInputProfiles()) {
4930 if (!inProfile->canOpenNewIo()) {
4931 ALOGE("Invalid Input profile max open count %u for profile %s",
4932 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4933 continue;
4934 }
4935 if (!inProfile->hasSupportedDevices()) {
4936 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4937 continue;
4938 }
4939 // chose first device present in profile's SupportedDevices also part of
4940 // available input devices
4941 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4942 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4943 if (availProfileDevices.isEmpty()) {
4944 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4945 continue;
4946 }
4947 sp<AudioInputDescriptor> inputDesc =
4948 new AudioInputDescriptor(inProfile, mpClientInterface);
4949
4950 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4951 status_t status = inputDesc->open(nullptr,
4952 availProfileDevices.itemAt(0),
4953 AUDIO_SOURCE_MIC,
4954 AUDIO_INPUT_FLAG_NONE,
4955 &input);
4956 if (status != NO_ERROR) {
4957 ALOGW("Cannot open input stream for device %s on hw module %s",
4958 availProfileDevices.toString().c_str(),
4959 hwModule->getName());
4960 continue;
4961 }
4962 for (const auto &device : availProfileDevices) {
4963 // give a valid ID to an attached device once confirmed it is reachable
4964 if (!device->isAttached()) {
4965 device->attach(hwModule);
4966 device->importAudioPortAndPickAudioProfile(inProfile, true);
4967 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004968 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004969 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4970 }
4971 }
4972 inputDesc->close();
4973 }
4974 }
4975}
4976
Eric Laurent98e38192018-02-15 18:31:53 -08004977void AudioPolicyManager::addOutput(audio_io_handle_t output,
4978 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004979{
Eric Laurent1c333e22014-05-20 10:48:17 -07004980 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004981 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004982 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004983 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004985}
4986
François Gaffie53615e22015-03-19 09:24:12 +01004987void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4988{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004989 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
4990 ALOGV("%s: removing primary output", __func__);
4991 mPrimaryOutput = nullptr;
4992 }
François Gaffie53615e22015-03-19 09:24:12 +01004993 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004994 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004995}
4996
Eric Laurent98e38192018-02-15 18:31:53 -08004997void AudioPolicyManager::addInput(audio_io_handle_t input,
4998 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004999{
Eric Laurent1c333e22014-05-20 10:48:17 -07005000 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005002}
Eric Laurente552edb2014-03-10 17:42:56 -07005003
François Gaffie11d30102018-11-02 16:09:09 +01005004status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005005 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005006 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005007{
François Gaffie11d30102018-11-02 16:09:09 +01005008 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005009 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005010 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005011
François Gaffie11d30102018-11-02 16:09:09 +01005012 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005013 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005014 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005015 }
Eric Laurente552edb2014-03-10 17:42:56 -07005016
Eric Laurent3b73df72014-03-11 09:06:29 -07005017 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005018 // first call getAudioPort to get the supported attributes from the HAL
5019 struct audio_port_v7 port = {};
5020 device->toAudioPort(&port);
5021 status_t status = mpClientInterface->getAudioPort(&port);
5022 if (status == NO_ERROR) {
5023 device->importAudioPort(port);
5024 }
5025
5026 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005027 for (size_t i = 0; i < mOutputs.size(); i++) {
5028 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005029 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005030 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005031 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5032 mOutputs.keyAt(i), device->toString().c_str());
5033 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005034 }
5035 }
5036 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005037 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005038 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005039 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5040 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005041 if (profile->supportsDevice(device)) {
5042 profiles.add(profile);
5043 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5044 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005045 }
5046 }
5047 }
5048
Eric Laurent7b279bb2015-12-14 10:18:23 -08005049 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005050
Eric Laurente552edb2014-03-10 17:42:56 -07005051 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005052 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005053 return BAD_VALUE;
5054 }
5055
5056 // open outputs for matching profiles if needed. Direct outputs are also opened to
5057 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5058 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005059 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005060
5061 // nothing to do if one output is already opened for this profile
5062 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005063 for (j = 0; j < outputs.size(); j++) {
5064 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005065 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005066 // matching profile: save the sample rates, format and channel masks supported
5067 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005068 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005069 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005070 }
Eric Laurente552edb2014-03-10 17:42:56 -07005071 break;
5072 }
5073 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005074 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 continue;
5076 }
5077
Eric Laurent3974e3b2017-12-07 17:58:43 -08005078 if (!profile->canOpenNewIo()) {
5079 ALOGW("Max Output number %u already opened for this profile %s",
5080 profile->maxOpenCount, profile->getTagName().c_str());
5081 continue;
5082 }
5083
Eric Laurent83efe1c2017-07-09 16:51:08 -07005084 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005085 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005086 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5087 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005088 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005089 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005090 profiles.removeAt(profile_index);
5091 profile_index--;
5092 } else {
5093 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005094 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005095 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005096 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5097 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005098 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005099 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005100
François Gaffie11d30102018-11-02 16:09:09 +01005101 if (device_distinguishes_on_address(deviceType)) {
5102 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5103 device->toString().c_str());
5104 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5105 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005106 }
Eric Laurente552edb2014-03-10 17:42:56 -07005107 ALOGV("checkOutputsForDevice(): adding output %d", output);
5108 }
5109 }
5110
5111 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005112 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005113 return BAD_VALUE;
5114 }
Eric Laurentd4692962014-05-05 18:13:44 -07005115 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005116 // check if one opened output is not needed any more after disconnecting one device
5117 for (size_t i = 0; i < mOutputs.size(); i++) {
5118 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005119 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005120 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005121 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005122 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005123 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005124 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005125 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5126 mOutputs.keyAt(i));
5127 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005128 }
Eric Laurente552edb2014-03-10 17:42:56 -07005129 }
5130 }
Eric Laurentd4692962014-05-05 18:13:44 -07005131 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005132 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005133 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5134 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005135 if (!profile->supportsDevice(device)) {
5136 continue;
5137 }
5138 ALOGV("checkOutputsForDevice(): "
5139 "clearing direct output profile %zu on module %s",
5140 j, hwModule->getName());
5141 profile->clearAudioProfiles();
5142 if (!profile->hasDynamicAudioProfile()) {
5143 continue;
5144 }
5145 // When a device is disconnected, if there is an IOProfile that contains dynamic
5146 // profiles and supports the disconnected device, call getAudioPort to repopulate
5147 // the capabilities of the devices that is supported by the IOProfile.
5148 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5149 if (supportedDevice == device ||
5150 !mAvailableOutputDevices.contains(supportedDevice)) {
5151 continue;
5152 }
5153 struct audio_port_v7 port;
5154 supportedDevice->toAudioPort(&port);
5155 status_t status = mpClientInterface->getAudioPort(&port);
5156 if (status == NO_ERROR) {
5157 supportedDevice->importAudioPort(port);
5158 }
Eric Laurente552edb2014-03-10 17:42:56 -07005159 }
5160 }
5161 }
5162 }
5163 return NO_ERROR;
5164}
5165
François Gaffie11d30102018-11-02 16:09:09 +01005166status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005167 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005168{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005169 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005170
François Gaffie11d30102018-11-02 16:09:09 +01005171 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005172 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005173 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005174 }
5175
Eric Laurentd4692962014-05-05 18:13:44 -07005176 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005177 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005178 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005179 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005180 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005181 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005182 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005183 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005184
François Gaffie11d30102018-11-02 16:09:09 +01005185 if (profile->supportsDevice(device)) {
5186 profiles.add(profile);
5187 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5188 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005189 }
5190 }
5191 }
5192
Eric Laurent0dd51852019-04-19 18:18:58 -07005193 if (profiles.isEmpty()) {
5194 ALOGW("%s: No input profile available for device %s",
5195 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005196 return BAD_VALUE;
5197 }
5198
5199 // open inputs for matching profiles if needed. Direct inputs are also opened to
5200 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5201 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5202
Eric Laurent1c333e22014-05-20 10:48:17 -07005203 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005204
Eric Laurentd4692962014-05-05 18:13:44 -07005205 // nothing to do if one input is already opened for this profile
5206 size_t input_index;
5207 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5208 desc = mInputs.valueAt(input_index);
5209 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005210 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005211 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005212 }
Eric Laurentd4692962014-05-05 18:13:44 -07005213 break;
5214 }
5215 }
5216 if (input_index != mInputs.size()) {
5217 continue;
5218 }
5219
Eric Laurent3974e3b2017-12-07 17:58:43 -08005220 if (!profile->canOpenNewIo()) {
5221 ALOGW("Max Input number %u already opened for this profile %s",
5222 profile->maxOpenCount, profile->getTagName().c_str());
5223 continue;
5224 }
5225
Eric Laurentfe231122017-11-17 17:48:06 -08005226 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005227 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005228 status_t status = desc->open(nullptr,
5229 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005230 AUDIO_SOURCE_MIC,
5231 AUDIO_INPUT_FLAG_NONE,
5232 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005233
Eric Laurentcf2c0212014-07-25 16:20:43 -07005234 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005235 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005236 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005237 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005238 mpClientInterface->setParameters(input, String8(param));
5239 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005240 }
François Gaffie11d30102018-11-02 16:09:09 +01005241 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005242 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005243 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005244 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005245 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005246 }
5247
Eric Laurent0dd51852019-04-19 18:18:58 -07005248 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005249 addInput(input, desc);
5250 }
5251 } // endif input != 0
5252
Eric Laurentcf2c0212014-07-25 16:20:43 -07005253 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005254 ALOGW("%s could not open input for device %s", __func__,
5255 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005256 profiles.removeAt(profile_index);
5257 profile_index--;
5258 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005259 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005260 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005261 }
Eric Laurentd4692962014-05-05 18:13:44 -07005262 ALOGV("checkInputsForDevice(): adding input %d", input);
5263 }
5264 } // end scan profiles
5265
5266 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005267 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005268 return BAD_VALUE;
5269 }
5270 } else {
5271 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005272 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005273 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005274 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005275 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005276 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005277 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005278 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005279 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5280 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005281 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005282 }
5283 }
5284 }
5285 } // end disconnect
5286
5287 return NO_ERROR;
5288}
5289
5290
Eric Laurente0720872014-03-11 09:30:41 -07005291void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005292{
5293 ALOGV("closeOutput(%d)", output);
5294
François Gaffie1c878552018-11-22 16:53:21 +01005295 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5296 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005297 ALOGW("closeOutput() unknown output %d", output);
5298 return;
5299 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005300 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005301 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005302
Eric Laurente552edb2014-03-10 17:42:56 -07005303 // look for duplicated outputs connected to the output being removed.
5304 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005305 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5306 if (dupOutput->isDuplicated() &&
5307 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5308 sp<SwAudioOutputDescriptor> remainingOutput =
5309 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005310 // As all active tracks on duplicated output will be deleted,
5311 // and as they were also referenced on the other output, the reference
5312 // count for their stream type must be adjusted accordingly on
5313 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005314 const bool wasActive = remainingOutput->isActive();
5315 // Note: no-op on the closing output where all clients has already been set inactive
5316 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005317 // stop() will be a no op if the output is still active but is needed in case all
5318 // active streams refcounts where cleared above
5319 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005320 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005321 }
Eric Laurente552edb2014-03-10 17:42:56 -07005322 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5323 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5324
5325 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005326 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005327 }
5328 }
5329
Eric Laurent05b90f82014-08-27 15:32:29 -07005330 nextAudioPortGeneration();
5331
François Gaffie1c878552018-11-22 16:53:21 +01005332 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005333 if (index >= 0) {
5334 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005335 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5336 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005337 mAudioPatches.removeItemsAt(index);
5338 mpClientInterface->onAudioPatchListUpdate();
5339 }
5340
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005341 if (closingOutputWasActive) {
5342 closingOutput->stop();
5343 }
François Gaffie1c878552018-11-22 16:53:21 +01005344 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005345
François Gaffie53615e22015-03-19 09:24:12 +01005346 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005347 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005348
5349 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5350 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005351 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005352 bool directOutputOpen = false;
5353 for (size_t i = 0; i < mOutputs.size(); i++) {
5354 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5355 directOutputOpen = true;
5356 break;
5357 }
5358 }
5359 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005360 ALOGV("no direct outputs open, reset MSD patches");
5361 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5362 // how output devices for patching are resolved. Avoid by caching and reusing the
5363 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5364 // devices to patch to. This may be complicated by the fact that devices may become
5365 // unavailable.
5366 setMsdPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005367 }
5368 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005369}
5370
5371void AudioPolicyManager::closeInput(audio_io_handle_t input)
5372{
5373 ALOGV("closeInput(%d)", input);
5374
5375 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5376 if (inputDesc == NULL) {
5377 ALOGW("closeInput() unknown input %d", input);
5378 return;
5379 }
5380
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005382
François Gaffie11d30102018-11-02 16:09:09 +01005383 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005384 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005385 if (index >= 0) {
5386 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5388 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005389 mAudioPatches.removeItemsAt(index);
5390 mpClientInterface->onAudioPatchListUpdate();
5391 }
5392
Eric Laurentfe231122017-11-17 17:48:06 -08005393 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005394 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005395
François Gaffie11d30102018-11-02 16:09:09 +01005396 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5397 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005398 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005399 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005400 }
Eric Laurente552edb2014-03-10 17:42:56 -07005401}
5402
François Gaffie11d30102018-11-02 16:09:09 +01005403SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5404 const DeviceVector &devices,
5405 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005406{
5407 SortedVector<audio_io_handle_t> outputs;
5408
François Gaffie11d30102018-11-02 16:09:09 +01005409 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005410 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005411 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005412 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005413 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005414 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005415 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005416 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005417 outputs.add(openOutputs.keyAt(i));
5418 }
5419 }
5420 return outputs;
5421}
5422
Mikhail Naganov37977152018-07-11 15:54:44 -07005423void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5424{
5425 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5426 // output is suspended before any tracks are moved to it
5427 checkA2dpSuspend();
5428 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005429 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005430 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005431 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005432 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005433 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5434 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5435 // configuration changes will ultimately be rerouted correctly. We can still avoid
5436 // unnecessary rerouting by caching and reusing the arguments to
5437 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5438 // This may be complicated by the fact that devices may become unavailable.
5439 setMsdPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005440 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005441 // an event that changed routing likely occurred, inform upper layers
5442 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005443}
5444
François Gaffiec005e562018-11-06 15:04:49 +01005445bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5446 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005447{
François Gaffiec005e562018-11-06 15:04:49 +01005448 return mEngine->getProductStrategyForAttributes(lAttr) ==
5449 mEngine->getProductStrategyForAttributes(rAttr);
5450}
5451
Francois Gaffieff1eb522020-05-06 18:37:04 +02005452void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5453{
5454 for (size_t i = 0; i < mAudioSources.size(); i++) {
5455 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5456 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005457 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5458 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005459 connectAudioSource(sourceDesc);
5460 }
5461 }
5462}
5463
5464void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5465{
5466 for (size_t i = 0; i < mAudioSources.size(); i++) {
5467 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5468 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5469 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5470 disconnectAudioSource(sourceDesc);
5471 }
5472 }
5473}
5474
François Gaffiec005e562018-11-06 15:04:49 +01005475void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5476{
5477 auto psId = mEngine->getProductStrategyForAttributes(attr);
5478
5479 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5480 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005481
François Gaffie11d30102018-11-02 16:09:09 +01005482 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5483 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005484
Eric Laurentc209fe42020-06-05 18:11:23 -07005485 uint32_t maxLatency = 0;
5486 bool invalidate = false;
5487 // take into account dynamic audio policies related changes: if a client is now associated
5488 // to a different policy mix than at creation time, invalidate corresponding stream
5489 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5490 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5491 if (desc->isDuplicated()) {
5492 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005493 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005494 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5495 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5496 continue;
5497 }
5498 sp<AudioPolicyMix> primaryMix;
5499 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5500 client->flags(), primaryMix, nullptr);
5501 if (status != OK) {
5502 continue;
5503 }
yucliuf4de36d2020-09-14 14:57:56 -07005504 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005505 invalidate = true;
5506 if (desc->isStrategyActive(psId)) {
5507 maxLatency = desc->latency();
5508 }
5509 break;
5510 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005511 }
5512 }
5513
Eric Laurentc209fe42020-06-05 18:11:23 -07005514 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005515 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5516 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005517 for (audio_io_handle_t srcOut : srcOutputs) {
5518 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005519 if (desc == nullptr) continue;
5520
5521 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005522 maxLatency = desc->latency();
5523 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005524
5525 if (invalidate) continue;
5526
5527 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005528 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005529 // a client on a non direct outputs has necessarily a linear PCM format
5530 // so we can call selectOutput() safely
5531 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5532 client->flags(),
5533 client->config().format,
5534 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005535 client->config().sample_rate,
5536 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005537 if (newOutput != srcOut) {
5538 invalidate = true;
5539 break;
5540 }
5541 } else {
5542 sp<IOProfile> profile = getProfileForOutput(newDevices,
5543 client->config().sample_rate,
5544 client->config().format,
5545 client->config().channel_mask,
5546 client->flags(),
5547 true /* directOnly */);
5548 if (profile != desc->mProfile) {
5549 invalidate = true;
5550 break;
5551 }
5552 }
5553 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005554 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005555
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005556 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005557 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005558 std::to_string(srcOutputs[0]).c_str(),
5559 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005560 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005561 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005562 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005563 if (desc == nullptr) continue;
5564
5565 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005566 setStrategyMute(psId, true, desc);
5567 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005568 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005569 }
François Gaffiec005e562018-11-06 15:04:49 +01005570 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005571 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005572 connectAudioSource(source);
5573 }
Eric Laurente552edb2014-03-10 17:42:56 -07005574 }
5575
François Gaffiec005e562018-11-06 15:04:49 +01005576 // Move effects associated to this stream from previous output to new output
5577 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005578 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005579 }
François Gaffiec005e562018-11-06 15:04:49 +01005580 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005581 if (invalidate) {
5582 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5583 mpClientInterface->invalidateStream(stream);
5584 }
Eric Laurente552edb2014-03-10 17:42:56 -07005585 }
5586 }
5587}
5588
Eric Laurente0720872014-03-11 09:30:41 -07005589void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
François Gaffiec005e562018-11-06 15:04:49 +01005591 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5592 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5593 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005594 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005595 }
Eric Laurente552edb2014-03-10 17:42:56 -07005596}
5597
Kevin Rocard153f92d2018-12-18 18:33:28 -08005598void AudioPolicyManager::checkSecondaryOutputs() {
5599 std::set<audio_stream_type_t> streamsToInvalidate;
5600 for (size_t i = 0; i < mOutputs.size(); i++) {
5601 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5602 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005603 sp<AudioPolicyMix> primaryMix;
5604 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005605 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005606 client->flags(), primaryMix, &secondaryMixes);
5607 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5608 for (auto &secondaryMix : secondaryMixes) {
5609 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5610 if (outputDesc != nullptr &&
5611 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5612 secondaryDescs.push_back(outputDesc);
5613 }
5614 }
5615
Kevin Rocard94114a22019-04-01 19:38:23 -07005616 if (status != OK ||
5617 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005618 client->getSecondaryOutputs().end(),
5619 secondaryDescs.begin(), secondaryDescs.end())) {
5620 streamsToInvalidate.insert(client->stream());
5621 }
5622 }
5623 }
5624 for (audio_stream_type_t stream : streamsToInvalidate) {
5625 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5626 mpClientInterface->invalidateStream(stream);
5627 }
5628}
5629
Eric Laurent2517af32020-11-25 15:31:27 +01005630bool AudioPolicyManager::isScoRequestedForComm() const {
5631 AudioDeviceTypeAddrVector devices;
5632 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5633 for (const auto &device : devices) {
5634 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5635 return true;
5636 }
5637 }
5638 return false;
5639}
5640
Eric Laurente0720872014-03-11 09:30:41 -07005641void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005642{
François Gaffie53615e22015-03-19 09:24:12 +01005643 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005644 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005645 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005646 return;
5647 }
5648
Eric Laurent3a4311c2014-03-17 12:00:47 -07005649 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005650 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5651 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005652 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005653
5654 // if suspended, restore A2DP output if:
5655 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005656 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005657 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005658 //
Eric Laurentf732e072016-08-03 19:30:28 -07005659 // if not suspended, suspend A2DP output if:
5660 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005661 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005662 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005663 //
5664 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005665 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005666 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005667 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005668 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005669
5670 mpClientInterface->restoreOutput(a2dpOutput);
5671 mA2dpSuspended = false;
5672 }
5673 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005674 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005675 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005676 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005677 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005678
5679 mpClientInterface->suspendOutput(a2dpOutput);
5680 mA2dpSuspended = true;
5681 }
5682 }
5683}
5684
François Gaffie11d30102018-11-02 16:09:09 +01005685DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5686 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005687{
François Gaffie11d30102018-11-02 16:09:09 +01005688 DeviceVector devices;
5689
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005690 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005691 if (index >= 0) {
5692 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005693 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005694 ALOGV("%s device %s forced by patch %d", __func__,
5695 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5696 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005697 }
5698 }
5699
Dean Wheatley514b4312020-06-17 21:45:00 +10005700 // Do not retrieve engine device for outputs through MSD
5701 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5702 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5703 return outputDesc->devices();
5704 }
5705
Eric Laurent97ac8712018-07-27 18:59:02 -07005706 // Honor explicit routing requests only if no client using default routing is active on this
5707 // input: a specific app can not force routing for other apps by setting a preferred device.
5708 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005709 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005710 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005711 if (device != nullptr) {
5712 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005713 }
5714
François Gaffiea807ef92018-11-05 10:44:33 +01005715 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5716 // of setForceUse / Default Bus device here
5717 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5718 if (device != nullptr) {
5719 return DeviceVector(device);
5720 }
5721
François Gaffiec005e562018-11-06 15:04:49 +01005722 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5723 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5724 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005725
François Gaffiec005e562018-11-06 15:04:49 +01005726 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005727 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5728 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005729 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005730 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5731 outputDesc->isStrategyActive(productStrategy)) {
5732 // Retrieval of devices for voice DL is done on primary output profile, cannot
5733 // check the route (would force modifying configuration file for this profile)
5734 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5735 break;
5736 }
Eric Laurente552edb2014-03-10 17:42:56 -07005737 }
François Gaffiec005e562018-11-06 15:04:49 +01005738 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005739 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005740}
5741
François Gaffie11d30102018-11-02 16:09:09 +01005742sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5743 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005744{
François Gaffie11d30102018-11-02 16:09:09 +01005745 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005746
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005747 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005748 if (index >= 0) {
5749 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005750 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005751 ALOGV("getNewInputDevice() device %s forced by patch %d",
5752 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5753 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005754 }
5755 }
5756
Eric Laurent97ac8712018-07-27 18:59:02 -07005757 // Honor explicit routing requests only if no client using default routing is active on this
5758 // input: a specific app can not force routing for other apps by setting a preferred device.
5759 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005760 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5761 if (device != nullptr) {
5762 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005763 }
5764
Eric Laurentdc95a252018-04-12 12:46:56 -07005765 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005766 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005767 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5768 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5769 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005770 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005771 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005772 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005773 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005774
Eric Laurente552edb2014-03-10 17:42:56 -07005775 return device;
5776}
5777
Eric Laurent794fde22016-03-11 09:50:45 -08005778bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5779 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005780 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005781}
5782
Eric Laurente0720872014-03-11 09:30:41 -07005783audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005784 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005785 // getOutputDevicesForStream's behavior for invalid streams.
5786 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5787 // device for music stream), but we want to return the empty set.
5788 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005789 return AUDIO_DEVICE_NONE;
5790 }
François Gaffie11d30102018-11-02 16:09:09 +01005791 DeviceVector activeDevices;
5792 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005793 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5794 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005795 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005796 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005797 }
François Gaffiec005e562018-11-06 15:04:49 +01005798 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005799 devices.merge(curDevices);
5800 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005801 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005802 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005803 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005804 }
5805 }
Eric Laurente552edb2014-03-10 17:42:56 -07005806 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005807
Eric Laurentb0688d62018-08-14 15:49:18 -07005808 // Favor devices selected on active streams if any to report correct device in case of
5809 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005810 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005811 devices = activeDevices;
5812 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005813 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5814 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005815 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005816 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005817 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005818 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005819 }
jiabin9a3361e2019-10-01 09:38:30 -07005820 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5821 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005822}
5823
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005824status_t AudioPolicyManager::getDevicesForAttributes(
5825 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5826 if (devices == nullptr) {
5827 return BAD_VALUE;
5828 }
5829 // check dynamic policies but only for primary descriptors (secondary not used for audible
5830 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005831 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005832 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005833 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005834 if (status != OK) {
5835 return status;
5836 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005837 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5838 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5839 devices->push_back(device);
5840 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005841 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005842 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5843 for (const auto& device : curDevices) {
5844 devices->push_back(device->getDeviceTypeAddr());
5845 }
5846 return NO_ERROR;
5847}
5848
Eric Laurente0720872014-03-11 09:30:41 -07005849void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005850 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005851 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005852 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005853 updateDevicesAndOutputs();
5854 break;
5855 default:
5856 break;
5857 }
5858}
5859
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005860uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005861
5862 // skip beacon mute management if a dedicated TTS output is available
5863 if (mTtsOutputAvailable) {
5864 return 0;
5865 }
5866
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005867 switch(event) {
5868 case STARTING_OUTPUT:
5869 mBeaconMuteRefCount++;
5870 break;
5871 case STOPPING_OUTPUT:
5872 if (mBeaconMuteRefCount > 0) {
5873 mBeaconMuteRefCount--;
5874 }
5875 break;
5876 case STARTING_BEACON:
5877 mBeaconPlayingRefCount++;
5878 break;
5879 case STOPPING_BEACON:
5880 if (mBeaconPlayingRefCount > 0) {
5881 mBeaconPlayingRefCount--;
5882 }
5883 break;
5884 }
5885
5886 if (mBeaconMuteRefCount > 0) {
5887 // any playback causes beacon to be muted
5888 return setBeaconMute(true);
5889 } else {
5890 // no other playback: unmute when beacon starts playing, mute when it stops
5891 return setBeaconMute(mBeaconPlayingRefCount == 0);
5892 }
5893}
5894
5895uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5896 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5897 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5898 // keep track of muted state to avoid repeating mute/unmute operations
5899 if (mBeaconMuted != mute) {
5900 // mute/unmute AUDIO_STREAM_TTS on all outputs
5901 ALOGV("\t muting %d", mute);
5902 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005903 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005904 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005905 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005906 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005907 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005908 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005909 maxLatency = latency;
5910 }
5911 }
5912 mBeaconMuted = mute;
5913 return maxLatency;
5914 }
5915 return 0;
5916}
5917
Eric Laurente0720872014-03-11 09:30:41 -07005918void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005919{
François Gaffiec005e562018-11-06 15:04:49 +01005920 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005921 mPreviousOutputs = mOutputs;
5922}
5923
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005924uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005925 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005926 uint32_t delayMs)
5927{
5928 // mute/unmute strategies using an incompatible device combination
5929 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5930 // if unmuting, unmute only after the specified delay
5931 if (outputDesc->isDuplicated()) {
5932 return 0;
5933 }
5934
5935 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005936 DeviceVector devices = outputDesc->devices();
5937 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005938
François Gaffiec005e562018-11-06 15:04:49 +01005939 auto productStrategies = mEngine->getOrderedProductStrategies();
5940 for (const auto &productStrategy : productStrategies) {
5941 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5942 DeviceVector curDevices =
5943 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5944 curDevices = curDevices.filter(outputDesc->supportedDevices());
5945 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005946 bool doMute = false;
5947
François Gaffiec005e562018-11-06 15:04:49 +01005948 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005949 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005950 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5951 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005952 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005953 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005954 }
Eric Laurent99401132014-05-07 19:48:15 -07005955 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005956 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005957 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005958 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005959 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005960 continue;
5961 }
François Gaffiec005e562018-11-06 15:04:49 +01005962 ALOGVV("%s() %s (curDevice %s)", __func__,
5963 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5964 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5965 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005966 if (mute) {
5967 // FIXME: should not need to double latency if volume could be applied
5968 // immediately by the audioflinger mixer. We must account for the delay
5969 // between now and the next time the audioflinger thread for this output
5970 // will process a buffer (which corresponds to one buffer size,
5971 // usually 1/2 or 1/4 of the latency).
5972 if (muteWaitMs < desc->latency() * 2) {
5973 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005974 }
5975 }
5976 }
5977 }
5978 }
5979 }
5980
Eric Laurent99401132014-05-07 19:48:15 -07005981 // temporary mute output if device selection changes to avoid volume bursts due to
5982 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005983 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005984 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5985 // temporary mute duration is conservatively set to 4 times the reported latency
5986 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5987 if (muteWaitMs < tempMuteWaitMs) {
5988 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005989 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005990 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5991 // make sure that we do not start the temporary mute period too early in case of
5992 // delayed device change
5993 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5994 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005995 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005996 }
5997 }
5998
Eric Laurente552edb2014-03-10 17:42:56 -07005999 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6000 if (muteWaitMs > delayMs) {
6001 muteWaitMs -= delayMs;
6002 usleep(muteWaitMs * 1000);
6003 return muteWaitMs;
6004 }
6005 return 0;
6006}
6007
François Gaffie11d30102018-11-02 16:09:09 +01006008uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6009 const DeviceVector &devices,
6010 bool force,
6011 int delayMs,
6012 audio_patch_handle_t *patchHandle,
6013 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006014{
François Gaffie11d30102018-11-02 16:09:09 +01006015 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006016 uint32_t muteWaitMs;
6017
6018 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006019 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6020 nullptr /* patchHandle */, requiresMuteCheck);
6021 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6022 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006023 return muteWaitMs;
6024 }
Eric Laurente552edb2014-03-10 17:42:56 -07006025
6026 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006027 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006028 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006029
François Gaffie11d30102018-11-02 16:09:09 +01006030 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6031
6032 if (!filteredDevices.isEmpty()) {
6033 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006034 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006035
6036 // if the outputs are not materially active, there is no need to mute.
6037 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006038 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006039 } else {
6040 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6041 muteWaitMs = 0;
6042 }
Eric Laurente552edb2014-03-10 17:42:56 -07006043
Eric Laurent79ea9582020-06-11 18:49:24 -07006044 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6045 // output profile or if new device is not supported AND previous device(s) is(are) still
6046 // available (otherwise reset device must be done on the output)
6047 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6048 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6049 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6050 // restore previous device after evaluating strategy mute state
6051 outputDesc->setDevices(prevDevices);
6052 return muteWaitMs;
6053 }
6054
Eric Laurente552edb2014-03-10 17:42:56 -07006055 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006056 // the requested device is AUDIO_DEVICE_NONE
6057 // OR the requested device is the same as current device
6058 // AND force is not specified
6059 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006060 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006061 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006062 !force && outputDesc->getPatchHandle() != 0) {
6063 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6064 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006065 return muteWaitMs;
6066 }
6067
François Gaffie11d30102018-11-02 16:09:09 +01006068 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006069
Eric Laurente552edb2014-03-10 17:42:56 -07006070 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006071 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006072 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006073 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006074 PatchBuilder patchBuilder;
6075 patchBuilder.addSource(outputDesc);
6076 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6077 for (const auto &filteredDevice : filteredDevices) {
6078 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006079 }
6080
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006081 // Add half reported latency to delayMs when muteWaitMs is null in order
6082 // to avoid disordered sequence of muting volume and changing devices.
6083 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6084 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006085 }
Eric Laurente552edb2014-03-10 17:42:56 -07006086
6087 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006088 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006089
6090 return muteWaitMs;
6091}
6092
Eric Laurentc75307b2015-03-17 15:29:32 -07006093status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006094 int delayMs,
6095 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006096{
Eric Laurent6a94d692014-05-20 11:18:06 -07006097 ssize_t index;
6098 if (patchHandle) {
6099 index = mAudioPatches.indexOfKey(*patchHandle);
6100 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006101 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006102 }
6103 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006104 return INVALID_OPERATION;
6105 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006106 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006107 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006108 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006109 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006110 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006111 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006112 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006113 return status;
6114}
6115
6116status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006117 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006118 bool force,
6119 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006120{
6121 status_t status = NO_ERROR;
6122
Eric Laurent1f2f2232014-06-02 12:01:23 -07006123 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006124 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6125 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006126
François Gaffie11d30102018-11-02 16:09:09 +01006127 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006128 PatchBuilder patchBuilder;
6129 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006130 // AUDIO_SOURCE_HOTWORD is for internal use only:
6131 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006132 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6133 auto result = usecase;
6134 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6135 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6136 }
6137 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006138 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006139 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006140 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006141 }
6142 }
6143 return status;
6144}
6145
Eric Laurent6a94d692014-05-20 11:18:06 -07006146status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6147 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006148{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006149 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006150 ssize_t index;
6151 if (patchHandle) {
6152 index = mAudioPatches.indexOfKey(*patchHandle);
6153 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006154 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006155 }
6156 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006157 return INVALID_OPERATION;
6158 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006159 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006160 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006161 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006162 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006163 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006164 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006165 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006166 return status;
6167}
6168
François Gaffie11d30102018-11-02 16:09:09 +01006169sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006170 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006171 audio_format_t& format,
6172 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006173 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006174{
6175 // Choose an input profile based on the requested capture parameters: select the first available
6176 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006177 //
6178 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6179 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006180
Glenn Kasten730b9262018-03-29 15:01:26 -07006181 sp<IOProfile> firstInexact;
6182 uint32_t updatedSamplingRate = 0;
6183 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6184 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006185 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006186 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006187 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006188 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006189 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006190 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006191 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006192 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006193 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006194 &channelMask /*updatedChannelMask*/,
6195 // FIXME ugly cast
6196 (audio_output_flags_t) flags,
6197 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006198 return profile;
6199 }
François Gaffie11d30102018-11-02 16:09:09 +01006200 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006201 samplingRate,
6202 &updatedSamplingRate,
6203 format,
6204 &updatedFormat,
6205 channelMask,
6206 &updatedChannelMask,
6207 // FIXME ugly cast
6208 (audio_output_flags_t) flags,
6209 false /*exactMatchRequiredForInputFlags*/)) {
6210 firstInexact = profile;
6211 }
6212
Eric Laurente552edb2014-03-10 17:42:56 -07006213 }
6214 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006215 if (firstInexact != nullptr) {
6216 samplingRate = updatedSamplingRate;
6217 format = updatedFormat;
6218 channelMask = updatedChannelMask;
6219 return firstInexact;
6220 }
Eric Laurente552edb2014-03-10 17:42:56 -07006221 return NULL;
6222}
6223
François Gaffieaaac0fd2018-11-22 17:56:39 +01006224float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6225 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006226 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006227 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006228{
jiabin9a3361e2019-10-01 09:38:30 -07006229 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006230
6231 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6232 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6233 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6234 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006235 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6236 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6237 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6238 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006239 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006240
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006241 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006242 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6243 mOutputs.isActive(ringVolumeSrc, 0)) {
6244 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006245 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006246 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006247 }
6248
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006249 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006250 if ((volumeSource != callVolumeSrc && (isInCall() ||
6251 mOutputs.isActiveLocally(callVolumeSrc))) &&
6252 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6253 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6254 volumeSource == alarmVolumeSrc ||
6255 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6256 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6257 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006258 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006259 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006260 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006261 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006262 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006263 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006264 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6265 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6266 // programmatically muted.
6267 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6268 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6269 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006270 bool exemptFromCapping =
6271 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6272 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006273 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6274 volumeSource, volumeDb);
6275 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006276 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6277 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6278 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006279 }
6280 }
Eric Laurente552edb2014-03-10 17:42:56 -07006281 // if a headset is connected, apply the following rules to ring tones and notifications
6282 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006283 // - always attenuate notifications volume by 6dB
6284 // - attenuate ring tones volume by 6dB unless music is not playing and
6285 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006286 // - if music is playing, always limit the volume to current music volume,
6287 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006288 if (!Intersection(deviceTypes,
6289 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6290 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006291 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6292 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006293 ((volumeSource == alarmVolumeSrc ||
6294 volumeSource == ringVolumeSrc) ||
6295 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6296 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6297 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6298 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6299 curves.canBeMuted()) {
6300
Eric Laurente552edb2014-03-10 17:42:56 -07006301 // when the phone is ringing we must consider that music could have been paused just before
6302 // by the music application and behave as if music was active if the last music track was
6303 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006304 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006305 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006306 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006307 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006308 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6309 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006310 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006311 float musicVolDb = computeVolume(musicCurves,
6312 musicVolumeSrc,
6313 musicCurves.getVolumeIndex(musicDevice),
6314 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006315 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6316 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6317 if (volumeDb > minVolDb) {
6318 volumeDb = minVolDb;
6319 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006320 }
jiabin9a3361e2019-10-01 09:38:30 -07006321 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6322 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006323 // on A2DP, also ensure notification volume is not too low compared to media when
6324 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006325 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006326 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006327 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6328 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006329 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6330 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006331 }
6332 }
jiabin9a3361e2019-10-01 09:38:30 -07006333 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006334 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006335 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006336 }
6337 }
6338
François Gaffie43c73442018-11-08 08:21:55 +01006339 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006340}
6341
Eric Laurent3839bc02018-07-10 18:33:34 -07006342int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006343 VolumeSource fromVolumeSource,
6344 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006345{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006346 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006347 return srcIndex;
6348 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006349 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6350 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006351 float minSrc = (float)srcCurves.getVolumeIndexMin();
6352 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6353 float minDst = (float)dstCurves.getVolumeIndexMin();
6354 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006355
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006356 // preserve mute request or correct range
6357 if (srcIndex < minSrc) {
6358 if (srcIndex == 0) {
6359 return 0;
6360 }
6361 srcIndex = minSrc;
6362 } else if (srcIndex > maxSrc) {
6363 srcIndex = maxSrc;
6364 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006365 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6366}
6367
François Gaffieaaac0fd2018-11-22 17:56:39 +01006368status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6369 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006370 int index,
6371 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006372 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006373 int delayMs,
6374 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006375{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006376 // do not change actual attributes volume if the attributes is muted
6377 if (outputDesc->isMuted(volumeSource)) {
6378 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6379 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006380 return NO_ERROR;
6381 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006382 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6383 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6384 bool isVoiceVolSrc = callVolSrc == volumeSource;
6385 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6386
Eric Laurent2517af32020-11-25 15:31:27 +01006387 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006388 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006389 // if sco and call follow same curves, bypass forceUseForComm
6390 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006391 ((isVoiceVolSrc && isScoRequested) ||
6392 (isBtScoVolSrc && !isScoRequested))) {
6393 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6394 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006395 // Do not return an error here as AudioService will always set both voice call
6396 // and bluetooth SCO volumes due to stream aliasing.
6397 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006398 }
jiabin9a3361e2019-10-01 09:38:30 -07006399 if (deviceTypes.empty()) {
6400 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006401 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006402
jiabin9a3361e2019-10-01 09:38:30 -07006403 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6404 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006405 // Force VoIP volume to max for bluetooth SCO device except if muted
6406 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006407 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006408 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006409 }
jiabin9a3361e2019-10-01 09:38:30 -07006410 outputDesc->setVolume(
6411 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006412
François Gaffieaaac0fd2018-11-22 17:56:39 +01006413 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006414 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006415 // 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 +01006416 if (isVoiceVolSrc) {
6417 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006418 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006419 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006420 }
Eric Laurent18fba842016-03-31 14:41:26 -07006421 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006422 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6423 mLastVoiceVolume = voiceVolume;
6424 }
6425 }
Eric Laurente552edb2014-03-10 17:42:56 -07006426 return NO_ERROR;
6427}
6428
Eric Laurentc75307b2015-03-17 15:29:32 -07006429void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006430 const DeviceTypeSet& deviceTypes,
6431 int delayMs,
6432 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006433{
jiabincd510522020-01-22 09:40:55 -08006434 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006435 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6436 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6437 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006438 curves.getVolumeIndex(deviceTypes),
6439 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006440 }
6441}
6442
François Gaffiec005e562018-11-06 15:04:49 +01006443void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6444 bool on,
6445 const sp<AudioOutputDescriptor>& outputDesc,
6446 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006447 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006448{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006449 std::vector<VolumeSource> sourcesToMute;
6450 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6451 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6452 toString(attributes).c_str(), on, outputDesc->getId());
6453 VolumeSource source = toVolumeSource(attributes);
6454 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6455 sourcesToMute.push_back(source);
6456 }
Eric Laurente552edb2014-03-10 17:42:56 -07006457 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006458 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006459 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006460 }
6461
Eric Laurente552edb2014-03-10 17:42:56 -07006462}
6463
François Gaffieaaac0fd2018-11-22 17:56:39 +01006464void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6465 bool on,
6466 const sp<AudioOutputDescriptor>& outputDesc,
6467 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006468 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006469{
jiabin9a3361e2019-10-01 09:38:30 -07006470 if (deviceTypes.empty()) {
6471 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006472 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006473 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006474 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006475 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006476 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006477 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6478 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6479 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006480 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006481 }
6482 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006483 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6484 // ignored
6485 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006486 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006487 if (!outputDesc->isMuted(volumeSource)) {
6488 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006489 return;
6490 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006491 if (outputDesc->decMuteCount(volumeSource) == 0) {
6492 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006493 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006494 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006495 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006496 delayMs);
6497 }
6498 }
6499}
6500
François Gaffie53615e22015-03-19 09:24:12 +01006501bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6502{
François Gaffiec005e562018-11-06 15:04:49 +01006503 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006504 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6505 return true;
6506 }
6507
6508 // has known usage?
6509 switch (paa->usage) {
6510 case AUDIO_USAGE_UNKNOWN:
6511 case AUDIO_USAGE_MEDIA:
6512 case AUDIO_USAGE_VOICE_COMMUNICATION:
6513 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6514 case AUDIO_USAGE_ALARM:
6515 case AUDIO_USAGE_NOTIFICATION:
6516 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6517 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6518 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6519 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6520 case AUDIO_USAGE_NOTIFICATION_EVENT:
6521 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6522 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6523 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6524 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006525 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006526 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006527 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006528 case AUDIO_USAGE_EMERGENCY:
6529 case AUDIO_USAGE_SAFETY:
6530 case AUDIO_USAGE_VEHICLE_STATUS:
6531 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006532 break;
6533 default:
6534 return false;
6535 }
6536 return true;
6537}
6538
François Gaffie2110e042015-03-24 08:41:51 +01006539audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6540{
6541 return mEngine->getForceUse(usage);
6542}
6543
6544bool AudioPolicyManager::isInCall()
6545{
6546 return isStateInCall(mEngine->getPhoneState());
6547}
6548
6549bool AudioPolicyManager::isStateInCall(int state)
6550{
6551 return is_state_in_call(state);
6552}
6553
Eric Laurent74b71512019-11-06 17:21:57 -08006554bool AudioPolicyManager::isCallAudioAccessible()
6555{
6556 audio_mode_t mode = mEngine->getPhoneState();
6557 return (mode == AUDIO_MODE_IN_CALL)
6558 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6559 || (mode == AUDIO_MODE_CALL_SCREEN);
6560}
6561
Eric Laurentd60560a2015-04-10 11:31:20 -07006562void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6563{
6564 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006565 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006566 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006567 sourceDesc->sinkDevice()->equals(deviceDesc))
6568 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006569 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006570 }
6571 }
6572
6573 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6574 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6575 bool release = false;
6576 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6577 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6578 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6579 source->ext.device.type == deviceDesc->type()) {
6580 release = true;
6581 }
6582 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006583 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006584 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6585 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6586 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006587 sink->ext.device.type == deviceDesc->type() &&
6588 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6589 || strncmp(sink->ext.device.address, address,
6590 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006591 release = true;
6592 }
6593 }
6594 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006595 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6596 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006597 }
6598 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006599
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006600 mInputs.clearSessionRoutesForDevice(deviceDesc);
6601
Francois Gaffie716e1432019-01-14 16:58:59 +01006602 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006603}
6604
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006605void AudioPolicyManager::modifySurroundFormats(
6606 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006607 std::unordered_set<audio_format_t> enforcedSurround(
6608 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006609 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6610 for (const auto& pair : mConfig.getSurroundFormats()) {
6611 allSurround.insert(pair.first);
6612 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6613 }
Phil Burk09bc4612016-02-24 15:58:15 -08006614
6615 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6616 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006617 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006618 // This is the resulting set of formats depending on the surround mode:
6619 // 'all surround' = allSurround
6620 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6621 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6622 // 'manual surround' = mManualSurroundFormats
6623 // AUTO: formats v 'enforced surround'
6624 // ALWAYS: formats v 'all surround' v 'enforced surround'
6625 // NEVER: formats ^ 'non-surround'
6626 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006627
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006628 std::unordered_set<audio_format_t> formatSet;
6629 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6630 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006631 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006632 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006633 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006634 formatSet.insert(*formatIter);
6635 }
6636 }
6637 } else {
6638 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6639 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006640 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006641
jiabin81772902018-04-02 17:52:27 -07006642 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006643 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006644 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6645 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6646 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006647 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006648 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6649 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6650 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006651 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006652 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006653 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006654 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006655 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006656 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006657}
6658
jiabin06e4bab2019-07-29 10:13:34 -07006659void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6660 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006661 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6662 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6663
6664 // If NEVER, then remove support for channelMasks > stereo.
6665 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006666 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6667 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006668 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6669 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006670 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006671 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006672 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006673 }
6674 }
jiabin81772902018-04-02 17:52:27 -07006675 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6676 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6677 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006678 bool supports5dot1 = false;
6679 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006680 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006681 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6682 supports5dot1 = true;
6683 break;
6684 }
6685 }
6686 // If not then add 5.1 support.
6687 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006688 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006689 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006690 }
Phil Burk09bc4612016-02-24 15:58:15 -08006691 }
6692}
6693
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006694void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006695 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006696 AudioProfileVector &profiles)
6697{
6698 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006699 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006700
François Gaffie112b0af2015-11-19 16:13:25 +01006701 // Format MUST be checked first to update the list of AudioProfile
6702 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006703 reply = mpClientInterface->getParameters(
6704 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006705 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006706 AudioParameter repliedParameters(reply);
6707 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006708 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006709 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6710 return;
6711 }
Phil Burk09bc4612016-02-24 15:58:15 -08006712 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006713 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006714 if (device == AUDIO_DEVICE_OUT_HDMI
6715 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006716 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006717 }
jiabin3e277cc2019-09-10 14:27:34 -07006718 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006719 }
François Gaffie112b0af2015-11-19 16:13:25 +01006720
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006721 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006722 ChannelMaskSet channelMasks;
6723 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006724 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006725 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006726
6727 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006728 reply = mpClientInterface->getParameters(
6729 ioHandle,
6730 requestedParameters.toString() + ";" +
6731 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006732 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006733 AudioParameter repliedParameters(reply);
6734 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006735 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006736 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006737 }
6738 }
6739 if (profiles.hasDynamicChannelsFor(format)) {
6740 reply = mpClientInterface->getParameters(ioHandle,
6741 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006742 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006743 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006744 AudioParameter repliedParameters(reply);
6745 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006746 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006747 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006748 if (device == AUDIO_DEVICE_OUT_HDMI
6749 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006750 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006751 }
François Gaffie112b0af2015-11-19 16:13:25 +01006752 }
6753 }
jiabin3e277cc2019-09-10 14:27:34 -07006754 addDynamicAudioProfileAndSort(
6755 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006756 }
6757}
Eric Laurentd60560a2015-04-10 11:31:20 -07006758
Mikhail Naganovdc769682018-05-04 15:34:08 -07006759status_t AudioPolicyManager::installPatch(const char *caller,
6760 audio_patch_handle_t *patchHandle,
6761 AudioIODescriptorInterface *ioDescriptor,
6762 const struct audio_patch *patch,
6763 int delayMs)
6764{
6765 ssize_t index = mAudioPatches.indexOfKey(
6766 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6767 *patchHandle : ioDescriptor->getPatchHandle());
6768 sp<AudioPatch> patchDesc;
6769 status_t status = installPatch(
6770 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6771 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006772 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006773 }
6774 return status;
6775}
6776
6777status_t AudioPolicyManager::installPatch(const char *caller,
6778 ssize_t index,
6779 audio_patch_handle_t *patchHandle,
6780 const struct audio_patch *patch,
6781 int delayMs,
6782 uid_t uid,
6783 sp<AudioPatch> *patchDescPtr)
6784{
6785 sp<AudioPatch> patchDesc;
6786 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6787 if (index >= 0) {
6788 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006789 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006790 }
6791
6792 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6793 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6794 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6795 if (status == NO_ERROR) {
6796 if (index < 0) {
6797 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006798 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006799 } else {
6800 patchDesc->mPatch = *patch;
6801 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006802 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006803 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006804 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006805 }
6806 nextAudioPortGeneration();
6807 mpClientInterface->onAudioPatchListUpdate();
6808 }
6809 if (patchDescPtr) *patchDescPtr = patchDesc;
6810 return status;
6811}
6812
jiabinbce0c1d2020-10-05 11:20:18 -07006813bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6814{
6815 const TrackClientVector activeClients = output->getActiveClients();
6816 if (activeClients.empty()) {
6817 return true;
6818 }
6819 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6820 if (index < 0) {
6821 ALOGE("%s, no audio patch found while there are active clients on output %d",
6822 __func__, output->getId());
6823 return false;
6824 }
6825 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6826 DeviceVector routedDevices;
6827 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6828 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6829 patchDesc->mPatch.sinks[i].id);
6830 if (device == nullptr) {
6831 ALOGE("%s, no audio device found with id(%d)",
6832 __func__, patchDesc->mPatch.sinks[i].id);
6833 return false;
6834 }
6835 routedDevices.add(device);
6836 }
6837 for (const auto& client : activeClients) {
6838 // TODO: b/175343099 only travel the valid client
6839 sp<DeviceDescriptor> preferredDevice =
6840 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6841 if (mEngine->getOutputDevicesForAttributes(
6842 client->attributes(), preferredDevice, false) == routedDevices) {
6843 return false;
6844 }
6845 }
6846 return true;
6847}
6848
6849sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6850 const sp<IOProfile>& profile, const DeviceVector& devices)
6851{
6852 for (const auto& device : devices) {
6853 // TODO: This should be checking if the profile supports the device combo.
6854 if (!profile->supportsDevice(device)) {
6855 return nullptr;
6856 }
6857 }
6858 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6859 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6860 status_t status = desc->open(nullptr, devices,
6861 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6862 if (status != NO_ERROR) {
6863 return nullptr;
6864 }
6865
6866 // Here is where the out_set_parameters() for card & device gets called
6867 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6868 const audio_devices_t deviceType = device->type();
6869 const String8 &address = String8(device->address().c_str());
6870 if (!address.isEmpty()) {
6871 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6872 mpClientInterface->setParameters(output, String8(param));
6873 free(param);
6874 }
6875 updateAudioProfiles(device, output, profile->getAudioProfiles());
6876 if (!profile->hasValidAudioProfile()) {
6877 ALOGW("%s() missing param", __func__);
6878 desc->close();
6879 return nullptr;
6880 } else if (profile->hasDynamicAudioProfile()) {
6881 desc->close();
6882 output = AUDIO_IO_HANDLE_NONE;
6883 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6884 profile->pickAudioProfile(
6885 config.sample_rate, config.channel_mask, config.format);
6886 config.offload_info.sample_rate = config.sample_rate;
6887 config.offload_info.channel_mask = config.channel_mask;
6888 config.offload_info.format = config.format;
6889
6890 status = desc->open(&config, devices,
6891 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6892 if (status != NO_ERROR) {
6893 return nullptr;
6894 }
6895 }
6896
6897 addOutput(output, desc);
6898 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6899 sp<AudioPolicyMix> policyMix;
6900 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6901 policyMix->setOutput(desc);
6902 desc->mPolicyMix = policyMix;
6903 } else {
6904 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6905 address.string());
6906 }
6907
6908 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6909 // no duplicated output for direct outputs and
6910 // outputs used by dynamic policy mixes
6911 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6912
6913 //TODO: configure audio effect output stage here
6914
6915 // open a duplicating output thread for the new output and the primary output
6916 sp<SwAudioOutputDescriptor> dupOutputDesc =
6917 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6918 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6919 if (status == NO_ERROR) {
6920 // add duplicated output descriptor
6921 addOutput(duplicatedOutput, dupOutputDesc);
6922 } else {
6923 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6924 mPrimaryOutput->mIoHandle, output);
6925 desc->close();
6926 removeOutput(output);
6927 nextAudioPortGeneration();
6928 return nullptr;
6929 }
6930 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006931 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6932 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
6933 mPrimaryOutput = desc;
6934 }
jiabinbce0c1d2020-10-05 11:20:18 -07006935 return desc;
6936}
6937
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006938} // namespace android