blob: e82691f0a9e36aff6f974bc72d654ece4176d9eb [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);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530275 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
276 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100277 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700278 // do not force device change on duplicated output because if device is 0, it will
279 // also force a device 0 for the two outputs it is duplicated to which may override
280 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100281 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100282 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700284 // always force when disconnecting (a non-duplicated device)
285 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100286 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700287 }
jiabinbce0c1d2020-10-05 11:20:18 -0700288 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
289 desc->devices() != activeMediaDevices &&
290 desc->supportsDevicesForPlayback(activeMediaDevices)) {
291 // Reopen the output to query the dynamic profiles when there is not active
292 // clients or all active clients will be rerouted. Otherwise, set the flag
293 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
294 // can be reopened to query dynamic profiles when all clients are inactive.
295 if (areAllActiveTracksRerouted(desc)) {
296 outputsToReopen.push_back(mOutputs.keyAt(i));
297 } else {
298 desc->mPendingReopenToQueryProfiles = true;
299 }
300 }
301 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
302 // Clear the flag that previously set for re-querying profiles.
303 desc->mPendingReopenToQueryProfiles = false;
304 }
305 }
306 for (const auto& output : outputsToReopen) {
307 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
308 closeOutput(output);
309 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
311
Eric Laurentd60560a2015-04-10 11:31:20 -0700312 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100313 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700314 }
315
Eric Laurent72aa32f2014-05-30 18:51:48 -0700316 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700317 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700318 } // end if is output device
319
Eric Laurente552edb2014-03-10 17:42:56 -0700320 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700321 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100322 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700323 switch (state)
324 {
325 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700326 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700327 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100328 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700329 return INVALID_OPERATION;
330 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700331
332 if (mAvailableInputDevices.add(device) < 0) {
333 return NO_MEMORY;
334 }
335
François Gaffie44481e72016-04-20 07:49:57 +0200336 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
337 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100338 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200339
Eric Laurent0dd51852019-04-19 18:18:58 -0700340 if (checkInputsForDevice(device, state) != NO_ERROR) {
341 mAvailableInputDevices.remove(device);
342
François Gaffie11d30102018-11-02 16:09:09 +0100343 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100344
345 mHwModules.cleanUpForDevice(device);
346
Eric Laurentd4692962014-05-05 18:13:44 -0700347 return INVALID_OPERATION;
348 }
349
Eric Laurentd4692962014-05-05 18:13:44 -0700350 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700351
352 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700353 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100355 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700356 return INVALID_OPERATION;
357 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700358
François Gaffie11d30102018-11-02 16:09:09 +0100359 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700360
361 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100362 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700363
François Gaffie11d30102018-11-02 16:09:09 +0100364 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700365
366 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100367
368 // remove device from mReportedFormatsMap cache
369 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700371
372 default:
François Gaffie11d30102018-11-02 16:09:09 +0100373 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700374 return BAD_VALUE;
375 }
376
Eric Laurent736a1022019-03-27 18:28:46 -0700377 // Propagate device availability to Engine
378 setEngineDeviceConnectionState(device, state);
379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700381 // As the input device list can impact the output device selection, update
382 // getDeviceForStrategy() cache
383 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700384
Eric Laurent87ffa392015-05-22 10:32:38 -0700385 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100386 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
387 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200389 // Reconnect Audio Source
390 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
391 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
392 checkAudioSourceForAttributes(attributes);
393 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700394 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700396 }
397
Eric Laurentb52c1522014-05-20 11:27:36 -0700398 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700400 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700401
François Gaffie11d30102018-11-02 16:09:09 +0100402 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700403 return BAD_VALUE;
404}
405
Eric Laurent736a1022019-03-27 18:28:46 -0700406void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
407 audio_policy_dev_state_t state) {
408
409 // the Engine does not have to know about remote submix devices used by dynamic audio policies
410 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
411 return;
412 }
413 mEngine->setDeviceConnectionState(device, state);
414}
415
416
Eric Laurente0720872014-03-11 09:30:41 -0700417audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100418 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700419{
Eric Laurent634b7142016-04-20 13:48:02 -0700420 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800421 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
422 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700423 (strlen(device_address) != 0)/*matchAddress*/);
424
425 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100426 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700427 device, device_address);
428 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
429 }
François Gaffie53615e22015-03-19 09:24:12 +0100430
Eric Laurent3a4311c2014-03-17 12:00:47 -0700431 DeviceVector *deviceVector;
432
Eric Laurente552edb2014-03-10 17:42:56 -0700433 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700435 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 deviceVector = &mAvailableInputDevices;
437 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100438 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700439 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 }
Eric Laurent634b7142016-04-20 13:48:02 -0700441
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800442 return (deviceVector->getDevice(
443 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800445}
446
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800447status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
448 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800449 const char *device_name,
450 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800451{
452 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700453 String8 reply;
454 AudioParameter param;
455 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800456
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800457 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
458 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800460 // connect/disconnect only 1 device at a time
461 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
462
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800463 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700464 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800466 // Nothing to do: device is not connected
467 return NO_ERROR;
468 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800469 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800470
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700471 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800472 // configure codecs.
473 // Handle two specific cases by sending a set parameter to
474 // configure A2DP codecs. No need to toggle device state.
475 // Case 1: A2DP active device switches from primary to primary
476 // module
477 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200478 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700479 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800480 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
481 if (availablePrimaryOutputDevices().contains(devDesc) &&
482 (module != 0 && module->getHandle() == primaryHandle)) {
483 reply = mpClientInterface->getParameters(
484 AUDIO_IO_HANDLE_NONE,
485 String8(AudioParameter::keyReconfigA2dpSupported));
486 AudioParameter repliedParameters(reply);
487 repliedParameters.getInt(
488 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
489 if (isReconfigA2dpSupported) {
490 const String8 key(AudioParameter::keyReconfigA2dp);
491 param.add(key, String8("true"));
492 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
493 devDesc->setEncodedFormat(encodedFormat);
494 return NO_ERROR;
495 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700496 }
497 }
cnx421bd2dcc42020-07-11 14:58:44 +0800498 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
499 for (size_t i = 0; i < mOutputs.size(); i++) {
500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
501 // mute media strategies and delay device switch by the largest
502 // This avoid sending the music tail into the earpiece or headset.
503 setStrategyMute(musicStrategy, true, desc);
504 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
505 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
506 nullptr, true /*fromCache*/).types());
507 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Toggle the device state: UNAVAILABLE -> AVAILABLE
509 // This will force reading again the device configuration
510 status = setDeviceConnectionState(device,
511 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 device_address, device_name,
513 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800514 if (status != NO_ERROR) {
515 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
516 status);
517 return status;
518 }
519
520 status = setDeviceConnectionState(device,
521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 if (status != NO_ERROR) {
524 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
525 status);
526 return status;
527 }
528
529 return NO_ERROR;
530}
531
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800532status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
533 std::vector<audio_format_t> *formats)
534{
535 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800536 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800537 std::unordered_set<audio_format_t> formatSet;
538 sp<HwModule> primaryModule =
539 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700540 if (primaryModule == nullptr) {
541 ALOGE("%s() unable to get primary module", __func__);
542 return NO_INIT;
543 }
jiabin9a3361e2019-10-01 09:38:30 -0700544 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
545 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800546 for (const auto& device : declaredDevices) {
547 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800548 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800549 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800550 return status;
551}
552
François Gaffie11d30102018-11-02 16:09:09 +0100553uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700554{
555 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100556 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700557 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700558
jiabin9a3361e2019-10-01 09:38:30 -0700559 if(!hasPrimaryOutput() ||
560 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700561 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700562 }
François Gaffie11d30102018-11-02 16:09:09 +0100563 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
564
Francois Gaffie716e1432019-01-14 16:58:59 +0100565 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100566 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100567 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100568
569 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100570 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700571
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200572 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700573 // release TX patch if any
574 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100575 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700576 mCallTxPatch.clear();
577 }
578
François Gaffie9eb18552018-11-05 10:33:26 +0100579 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700580 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100581 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700582 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100583 // retrieve Rx Source and Tx Sink device descriptors
584 sp<DeviceDescriptor> rxSourceDevice =
585 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
586 String8(),
587 AUDIO_FORMAT_DEFAULT);
588 sp<DeviceDescriptor> txSinkDevice =
589 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
590 String8(),
591 AUDIO_FORMAT_DEFAULT);
592
593 // RX and TX Telephony device are declared by Primary Audio HAL
594 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
595 (telephonyRxModule->getHalVersionMajor() >= 3)) {
596 if (rxSourceDevice == 0 || txSinkDevice == 0) {
597 // RX / TX Telephony device(s) is(are) not currently available
598 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
599 return muteWaitMs;
600 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100601 // createAudioPatchInternal now supports both HW / SW bridging
602 createRxPatch = true;
603 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100604 } else {
605 // If the RX device is on the primary HW module, then use legacy routing method for
606 // voice calls via setOutputDevice() on primary output.
607 // Otherwise, create two audio patches for TX and RX path.
608 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
609 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610 // If the TX device is also on the primary HW module, setOutputDevice() will take care
611 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100612 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
613 (txSinkDevice != 0);
614 }
615 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
616 // Otherwise, create two audio patches for TX and RX path.
617 if (!createRxPatch) {
618 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700619 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200620 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800621 // If the TX device is on the primary HW module but RX device is
622 // on other HW module, SinkMetaData of telephony input should handle it
623 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700625 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100626 // terminate active capture if on the same HW module as the call TX source device
627 // FIXME: would be better to refine to only inputs whose profile connects to the
628 // call TX device but this information is not in the audio patch and logic here must be
629 // symmetric to the one in startInput()
630 for (const auto& activeDesc : mInputs.getActiveInputs()) {
631 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
632 closeActiveClients(activeDesc);
633 }
634 }
François Gaffie9eb18552018-11-05 10:33:26 +0100635 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800636 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700637
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800638 return muteWaitMs;
639}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700640
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800641sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100642 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700643 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700644
François Gaffie11d30102018-11-02 16:09:09 +0100645 if (device == nullptr) {
646 return nullptr;
647 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100648
649 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800650 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100651 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800652 addSource(mAvailableInputDevices.getDevice(
653 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800654 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100655 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800656 addSink(mAvailableOutputDevices.getDevice(
657 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800658 }
659
François Gaffieafd4cea2019-11-18 15:50:22 +0100660 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
661 status_t status =
662 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
663 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
664 if (status != NO_ERROR || index < 0) {
665 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
666 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800667 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100668 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800669}
670
Mikhail Naganov100f0122018-11-29 11:22:16 -0800671bool AudioPolicyManager::isDeviceOfModule(
672 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
673 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
674 if (module != 0) {
675 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
676 .indexOf(devDesc) != NAME_NOT_FOUND
677 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
678 .indexOf(devDesc) != NAME_NOT_FOUND;
679 }
680 return false;
681}
682
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200683void AudioPolicyManager::connectTelephonyRxAudioSource()
684{
685 disconnectTelephonyRxAudioSource();
686 const struct audio_port_config source = {
687 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
688 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
689 };
690 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
691 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
692 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
693}
694
695void AudioPolicyManager::disconnectTelephonyRxAudioSource()
696{
697 stopAudioSource(mCallRxSourceClientPort);
698 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
699}
700
Eric Laurente0720872014-03-11 09:30:41 -0700701void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700702{
703 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100704 // store previous phone state for management of sonification strategy below
705 int oldState = mEngine->getPhoneState();
706
707 if (mEngine->setPhoneState(state) != NO_ERROR) {
708 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700709 return;
710 }
François Gaffie2110e042015-03-24 08:41:51 +0100711 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700712 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700713 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700714 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800715 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 }
717
François Gaffie2110e042015-03-24 08:41:51 +0100718 /**
719 * Switching to or from incall state or switching between telephony and VoIP lead to force
720 * routing command.
721 */
Eric Laurent74b71512019-11-06 17:21:57 -0800722 bool force = ((isStateInCall(oldState) != isStateInCall(state))
723 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700724
725 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700726 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700727
Eric Laurente552edb2014-03-10 17:42:56 -0700728 int delayMs = 0;
729 if (isStateInCall(state)) {
730 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100731 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
732 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700733 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700735 // mute media and sonification strategies and delay device switch by the largest
736 // latency of any output where either strategy is active.
737 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100738 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
739 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
740 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700741 (delayMs < (int)desc->latency()*2)) {
742 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700743 }
François Gaffiec005e562018-11-06 15:04:49 +0100744 setStrategyMute(musicStrategy, true, desc);
745 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
746 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
747 nullptr, true /*fromCache*/).types());
748 setStrategyMute(sonificationStrategy, true, desc);
749 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
750 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
751 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700752 }
753 }
754
Eric Laurent87ffa392015-05-22 10:32:38 -0700755 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100756 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700757 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100758 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700759 // force routing command to audio hardware when ending call
760 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100761 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
762 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700763 }
Eric Laurente552edb2014-03-10 17:42:56 -0700764
Eric Laurent87ffa392015-05-22 10:32:38 -0700765 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100766 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700767 } else if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768 disconnectTelephonyRxAudioSource();
Eric Laurent87ffa392015-05-22 10:32:38 -0700769 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100770 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700771 mCallTxPatch.clear();
772 }
François Gaffie11d30102018-11-02 16:09:09 +0100773 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700774 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100775 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700776 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700778
779 // reevaluate routing on all outputs in case tracks have been started during the call
780 for (size_t i = 0; i < mOutputs.size(); i++) {
781 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100782 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700783 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100784 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700785 }
786 }
787
Eric Laurente552edb2014-03-10 17:42:56 -0700788 if (isStateInCall(state)) {
789 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700790 // force reevaluating accessibility routing when call starts
791 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700792 }
793
794 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100795 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
796 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700797}
798
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700799audio_mode_t AudioPolicyManager::getPhoneState() {
800 return mEngine->getPhoneState();
801}
802
Eric Laurente0720872014-03-11 09:30:41 -0700803void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100804 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700805{
François Gaffie2110e042015-03-24 08:41:51 +0100806 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700807 if (config == mEngine->getForceUse(usage)) {
808 return;
809 }
Eric Laurente552edb2014-03-10 17:42:56 -0700810
François Gaffie2110e042015-03-24 08:41:51 +0100811 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
812 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
813 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700814 }
François Gaffie2110e042015-03-24 08:41:51 +0100815 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
816 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
817 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700818
819 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700820 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800821
Eric Laurent22fcda22019-05-17 16:28:47 -0700822 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
823 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
824 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
825 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
826 }
827
Eric Laurentdc462862016-07-19 12:29:53 -0700828 //FIXME: workaround for truncated touch sounds
829 // to be removed when the problem is handled by system UI
830 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700831 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
832 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
833 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700834
835 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100836 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700837}
838
Eric Laurente0720872014-03-11 09:30:41 -0700839void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700840{
841 ALOGV("setSystemProperty() property %s, value %s", property, value);
842}
843
Michael Chana94fbb22018-04-24 14:31:19 +1000844// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
845// search to profiles for direct outputs.
846sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100847 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000848 uint32_t samplingRate,
849 audio_format_t format,
850 audio_channel_mask_t channelMask,
851 audio_output_flags_t flags,
852 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700853{
Michael Chana94fbb22018-04-24 14:31:19 +1000854 if (directOnly) {
855 // only retain flags that will drive the direct output profile selection
856 // if explicitly requested
857 static const uint32_t kRelevantFlags =
858 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700859 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000860 flags =
861 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
862 }
Eric Laurent861a6282015-05-18 15:40:16 -0700863
864 sp<IOProfile> profile;
865
Mikhail Naganovd4120142017-12-06 15:49:22 -0800866 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800867 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100868 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700869 samplingRate, NULL /*updatedSamplingRate*/,
870 format, NULL /*updatedFormat*/,
871 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700872 flags)) {
873 continue;
874 }
875 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100876 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700877 continue;
878 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800879 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700880 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800881 continue;
882 }
Michael Chana94fbb22018-04-24 14:31:19 +1000883 if (!directOnly) return curProfile;
884 // when searching for direct outputs, if several profiles are compatible, give priority
885 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100886 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700887 continue;
888 }
889 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100890 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700891 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700892 }
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
894 }
Eric Laurent861a6282015-05-18 15:40:16 -0700895 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700896}
897
Eric Laurentf4e63452017-11-06 19:31:46 +0000898audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffiec005e562018-11-06 15:04:49 +0100900 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800901
902 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
903 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
904 // format, flags, etc. This may result in some discrepancy for functions that utilize
905 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
906 // and AudioSystem::getOutputSamplingRate().
907
François Gaffie11d30102018-11-02 16:09:09 +0100908 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700909 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700910
François Gaffie11d30102018-11-02 16:09:09 +0100911 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
912 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000913 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914}
915
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700916status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
917 const audio_attributes_t *srcAttr,
918 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700919{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700920 if (srcAttr != NULL) {
921 if (!isValidAttributes(srcAttr)) {
922 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
923 __func__,
924 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
925 srcAttr->tags);
926 return BAD_VALUE;
927 }
928 *dstAttr = *srcAttr;
929 } else {
930 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
931 ALOGE("%s: invalid stream type", __func__);
932 return BAD_VALUE;
933 }
François Gaffiec005e562018-11-06 15:04:49 +0100934 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700935 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700936
937 // Only honor audibility enforced when required. The client will be
938 // forced to reconnect if the forced usage changes.
939 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700940 dstAttr->flags = static_cast<audio_flags_mask_t>(
941 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700942 }
943
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700944 return NO_ERROR;
945}
946
Kevin Rocard153f92d2018-12-18 18:33:28 -0800947status_t AudioPolicyManager::getOutputForAttrInt(
948 audio_attributes_t *resultAttr,
949 audio_io_handle_t *output,
950 audio_session_t session,
951 const audio_attributes_t *attr,
952 audio_stream_type_t *stream,
953 uid_t uid,
954 const audio_config_t *config,
955 audio_output_flags_t *flags,
956 audio_port_handle_t *selectedDeviceId,
957 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700958 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800959 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700960{
François Gaffiec005e562018-11-06 15:04:49 +0100961 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100962 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100963 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100964 const sp<DeviceDescriptor> requestedDevice =
965 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
966
Eric Laurent8a1095a2019-11-08 14:44:16 -0800967 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700968 status_t status = getAudioAttributes(resultAttr, attr, *stream);
969 if (status != NO_ERROR) {
970 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700971 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700972 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700973 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700974 }
François Gaffiec005e562018-11-06 15:04:49 +0100975 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700976
François Gaffiec005e562018-11-06 15:04:49 +0100977 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
978 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700979
Kevin Rocard153f92d2018-12-18 18:33:28 -0800980 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
981 // otherwise, fallback to the dynamic policies, if none match, query the engine.
982 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700983 sp<AudioPolicyMix> primaryMix;
984 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700985 if (status != OK) {
986 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800987 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700988
Kevin Rocard153f92d2018-12-18 18:33:28 -0800989 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700990 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800991
992 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700993 if ((usePrimaryOutputFromPolicyMixes
994 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800995 && !audio_is_linear_pcm(config->format)) {
996 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800997 return BAD_VALUE;
998 }
999 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001000 sp<DeviceDescriptor> deviceDesc =
1001 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1002 primaryMix->mDeviceAddress,
1003 AUDIO_FORMAT_DEFAULT);
1004 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001005 if (deviceDesc != nullptr
1006 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001007 audio_io_handle_t newOutput;
1008 status = openDirectOutput(
1009 *stream, session, config,
1010 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1011 DeviceVector(deviceDesc), &newOutput);
1012 if (status != NO_ERROR) {
1013 policyDesc = nullptr;
1014 } else {
1015 policyDesc = mOutputs.valueFor(newOutput);
1016 primaryMix->setOutput(policyDesc);
1017 }
1018 }
1019 if (policyDesc != nullptr) {
1020 policyDesc->mPolicyMix = primaryMix;
1021 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001022 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001023
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001024 ALOGV("getOutputForAttr() returns output %d", *output);
1025 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1026 *outputType = API_OUT_MIX_PLAYBACK;
1027 } else {
1028 *outputType = API_OUTPUT_LEGACY;
1029 }
1030 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001031 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001032 }
François Gaffiec005e562018-11-06 15:04:49 +01001033 // Virtual sources must always be dynamicaly or explicitly routed
1034 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1035 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1036 return BAD_VALUE;
1037 }
1038 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1039 // in order to let the choice of the order to future vendor engine
1040 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001041
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001042 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001043 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001044 }
1045
Nadav Barb2f18162018-07-18 13:01:53 +03001046 // Set incall music only if device was explicitly set, and fallback to the device which is
1047 // chosen by the engine if not.
1048 // FIXME: provide a more generic approach which is not device specific and move this back
1049 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001050 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001051 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001052 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001053 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001054 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001055 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001056 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001057 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001058 }
1059 }
1060
François Gaffiec005e562018-11-06 15:04:49 +01001061 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1062 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1063 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001064
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001065 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001066 if (!msdDevices.isEmpty()) {
1067 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Michael Chan6fb34492020-12-08 15:44:49 +11001068 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001069 ALOGV("%s() Using MSD devices %s instead of devices %s",
1070 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001071 } else {
1072 *output = AUDIO_IO_HANDLE_NONE;
1073 }
1074 }
1075 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001076 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001077 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001078 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001079 if (*output == AUDIO_IO_HANDLE_NONE) {
1080 return INVALID_OPERATION;
1081 }
Paul McLeanaa981192015-03-21 09:55:15 -07001082
François Gaffiec005e562018-11-06 15:04:49 +01001083 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001084 for (auto &outputDevice : outputDevices) {
1085 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1086 *selectedDeviceId = outputDevice->getId();
1087 break;
1088 }
1089 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001090
Eric Laurent8a1095a2019-11-08 14:44:16 -08001091 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1092 *outputType = API_OUTPUT_TELEPHONY_TX;
1093 } else {
1094 *outputType = API_OUTPUT_LEGACY;
1095 }
1096
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001097 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1098
1099 return NO_ERROR;
1100}
1101
1102status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1103 audio_io_handle_t *output,
1104 audio_session_t session,
1105 audio_stream_type_t *stream,
1106 uid_t uid,
1107 const audio_config_t *config,
1108 audio_output_flags_t *flags,
1109 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001110 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001111 std::vector<audio_io_handle_t> *secondaryOutputs,
1112 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113{
1114 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1115 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1116 return INVALID_OPERATION;
1117 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001118 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001119 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001120 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001121 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001122 const sp<DeviceDescriptor> requestedDevice =
1123 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1124
1125 // Prevent from storing invalid requested device id in clients
1126 const audio_port_handle_t sanitizedRequestedPortId =
1127 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1128 *selectedDeviceId = sanitizedRequestedPortId;
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001131 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001132 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001133 if (status != NO_ERROR) {
1134 return status;
1135 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001136 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001137 if (secondaryOutputs != nullptr) {
1138 for (auto &secondaryMix : secondaryMixes) {
1139 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1140 if (outputDesc != nullptr &&
1141 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1142 secondaryOutputs->push_back(outputDesc->mIoHandle);
1143 weakSecondaryOutputDescs.push_back(outputDesc);
1144 }
1145 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001146 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147
Eric Laurent8fc147b2018-07-22 19:13:55 -07001148 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001149 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001150 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001151 };
jiabin4ef93452019-09-10 14:29:54 -07001152 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001153
Eric Laurentc209fe42020-06-05 18:11:23 -07001154 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001155 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001157 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001158 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001159 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001161 std::move(weakSecondaryOutputDescs),
1162 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001163 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001164
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001165 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1166 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001167
Eric Laurente83b55d2014-11-14 10:06:21 -08001168 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001169}
1170
Eric Laurentc529cf62020-04-17 18:19:10 -07001171status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1172 audio_session_t session,
1173 const audio_config_t *config,
1174 audio_output_flags_t flags,
1175 const DeviceVector &devices,
1176 audio_io_handle_t *output) {
1177
1178 *output = AUDIO_IO_HANDLE_NONE;
1179
1180 // skip direct output selection if the request can obviously be attached to a mixed output
1181 // and not explicitly requested
1182 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1183 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1184 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1185 return NAME_NOT_FOUND;
1186 }
1187
1188 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1189 // This prevents creating an offloaded track and tearing it down immediately after start
1190 // when audioflinger detects there is an active non offloadable effect.
1191 // FIXME: We should check the audio session here but we do not have it in this context.
1192 // This may prevent offloading in rare situations where effects are left active by apps
1193 // in the background.
1194 sp<IOProfile> profile;
1195 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1196 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1197 profile = getProfileForOutput(
1198 devices, config->sample_rate, config->format, config->channel_mask,
1199 flags, true /* directOnly */);
1200 }
1201
1202 if (profile == nullptr) {
1203 return NAME_NOT_FOUND;
1204 }
1205
1206 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1207 for (size_t i = 0; i < mOutputs.size(); i++) {
1208 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1209 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1210 // reuse direct output if currently open by the same client
1211 // and configured with same parameters
1212 if ((config->sample_rate == desc->getSamplingRate()) &&
1213 (config->format == desc->getFormat()) &&
1214 (config->channel_mask == desc->getChannelMask()) &&
1215 (session == desc->mDirectClientSession)) {
1216 desc->mDirectOpenCount++;
1217 ALOGI("%s reusing direct output %d for session %d", __func__,
1218 mOutputs.keyAt(i), session);
1219 *output = mOutputs.keyAt(i);
1220 return NO_ERROR;
1221 }
1222 }
1223 }
1224
1225 if (!profile->canOpenNewIo()) {
1226 return NAME_NOT_FOUND;
1227 }
1228
1229 sp<SwAudioOutputDescriptor> outputDesc =
1230 new SwAudioOutputDescriptor(profile, mpClientInterface);
1231
Michael Chan6fb34492020-12-08 15:44:49 +11001232 // An MSD patch may be using the only output stream that can service this request. Release
1233 // all MSD patches to prioritize this request over any active output on MSD.
1234 releaseMsdPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001235
1236 status_t status = outputDesc->open(config, devices, stream, flags, output);
1237
1238 // only accept an output with the requested parameters
1239 if (status != NO_ERROR ||
1240 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1241 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1242 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1243 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1244 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1245 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1246 config->channel_mask, outputDesc->getChannelMask());
1247 if (*output != AUDIO_IO_HANDLE_NONE) {
1248 outputDesc->close();
1249 }
1250 // fall back to mixer output if possible when the direct output could not be open
1251 if (audio_is_linear_pcm(config->format) &&
1252 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1253 return NAME_NOT_FOUND;
1254 }
1255 *output = AUDIO_IO_HANDLE_NONE;
1256 return BAD_VALUE;
1257 }
1258 outputDesc->mDirectOpenCount = 1;
1259 outputDesc->mDirectClientSession = session;
1260
1261 addOutput(*output, outputDesc);
1262 mPreviousOutputs = mOutputs;
1263 ALOGV("%s returns new direct output %d", __func__, *output);
1264 mpClientInterface->onAudioPortListUpdate();
1265 return NO_ERROR;
1266}
1267
François Gaffie11d30102018-11-02 16:09:09 +01001268audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1269 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001270 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001271 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001272 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001273 audio_output_flags_t *flags,
1274 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001275{
Andy Hungc88b0642018-04-27 15:42:35 -07001276 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001277
jiabine375d412019-02-26 12:54:53 -08001278 // Discard haptic channel mask when forcing muting haptic channels.
1279 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001280 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1281 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001282
Eric Laurente552edb2014-03-10 17:42:56 -07001283 // open a direct output if required by specified parameters
1284 //force direct flag if offload flag is set: offloading implies a direct output stream
1285 // and all common behaviors are driven by checking only the direct flag
1286 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001287 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1288 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001289 }
Nadav Bar766fb022018-01-07 12:18:03 +02001290 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1291 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001292 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001293 // only allow deep buffering for music stream type
1294 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001295 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001296 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001297 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001298 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1299 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001300 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001301 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001302 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001303 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001304 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001305 audio_is_linear_pcm(config->format) &&
1306 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001307 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001308 AUDIO_OUTPUT_FLAG_DIRECT);
1309 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001310 }
Eric Laurente552edb2014-03-10 17:42:56 -07001311
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 audio_config_t directConfig = *config;
1313 directConfig.channel_mask = channelMask;
1314 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1315 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001316 return output;
1317 }
1318
Eric Laurent14cbfca2016-03-17 09:42:16 -07001319 // A request for HW A/V sync cannot fallback to a mixed output because time
1320 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001321 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001322 return AUDIO_IO_HANDLE_NONE;
1323 }
1324
Eric Laurente552edb2014-03-10 17:42:56 -07001325 // ignoring channel mask due to downmix capability in mixer
1326
1327 // open a non direct output
1328
1329 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001330 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001331 // get which output is suitable for the specified stream. The actual
1332 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001333 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001334
Eric Laurent8838a382014-09-08 16:44:28 -07001335 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001336 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001337 output = selectOutput(
1338 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
François Gaffie11d30102018-11-02 16:09:09 +01001340 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001341 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001342 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001343
Eric Laurente552edb2014-03-10 17:42:56 -07001344 return output;
1345}
1346
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001347sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001348 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1349 mAvailableInputDevices);
1350 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1351}
1352
1353DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1354 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1355 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001356}
1357
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001358const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1359 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001360 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1361 if (msdModule != 0) {
1362 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1363 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1364 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1365 const struct audio_port_config *source = &patch->mPatch.sources[j];
1366 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1367 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001368 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001369 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001370 }
1371 }
1372 }
1373 return msdPatches;
1374}
1375
François Gaffie11d30102018-11-02 16:09:09 +01001376status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001377 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1378{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001379 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001380 if (msdModule == nullptr) {
1381 ALOGE("%s() unable to get MSD module", __func__);
1382 return NO_INIT;
1383 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001384 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001385 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001386 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 return NO_INIT;
1388 }
1389 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1390 if (inputProfiles.isEmpty()) {
1391 ALOGE("%s() no input profiles for MSD module", __func__);
1392 return NO_INIT;
1393 }
1394 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1395 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001396 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001397 return NO_INIT;
1398 }
1399 AudioProfileVector msdProfiles;
1400 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1401 for (const auto &inProfile : inputProfiles) {
1402 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001403 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001404 }
1405 }
1406 AudioProfileVector deviceProfiles;
1407 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001408 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
1409 outProfile->supportsDevice(outputDevice)) {
jiabin3e277cc2019-09-10 14:27:34 -07001410 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 }
1412 }
1413 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001414 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001416 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001417 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001418 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1419 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001420 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001421 }
1422 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1423 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1424 sinkConfig->format = bestSinkConfig.format;
1425 // For encoded streams force direct flag to prevent downstream mixing.
1426 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1427 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001428 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1429 // For formats compatible with IEC61937 encapsulation, assume that
1430 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1431 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1432 // raw and IEC61937 framed streams.
1433 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1434 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1435 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001436 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1437 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1438 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1439 sourceConfig->format = bestSinkConfig.format;
1440 // Copy input stream directly without any processing (e.g. resampling).
1441 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1442 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1443 if (hwAvSync) {
1444 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1445 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1446 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1447 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1448 }
1449 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1450 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1451 sinkConfig->config_mask |= config_mask;
1452 sourceConfig->config_mask |= config_mask;
1453 return NO_ERROR;
1454}
1455
François Gaffie11d30102018-11-02 16:09:09 +01001456PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001457{
1458 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001459 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001460 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1461 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1462 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1463 // For now, we just forcefully try with HwAvSync first.
1464 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1465 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1466 getBestMsdAudioProfileFor(
1467 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1468 if (res == NO_ERROR) {
1469 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1470 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1471 }
1472 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1473 " supporting PCM format conversion.", __func__);
1474 return patchBuilder;
1475}
1476
Michael Chan6fb34492020-12-08 15:44:49 +11001477status_t AudioPolicyManager::setMsdPatches(const DeviceVector *outputDevices) {
1478 DeviceVector devices;
1479 if (outputDevices != nullptr && outputDevices->size() > 0) {
1480 devices.add(*outputDevices);
1481 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001482 // Use media strategy for unspecified output device. This should only
1483 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1484 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001485 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001486 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001487 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001488 }
Michael Chan6fb34492020-12-08 15:44:49 +11001489 std::vector<PatchBuilder> patchesToCreate;
1490 for (auto i = 0u; i < devices.size(); ++i) {
1491 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
1492 patchesToCreate.push_back(buildMsdPatch(devices[i]));
1493 }
1494 // Retain only the MSD patches associated with outputDevices request.
1495 // Tear down the others, and create new ones as needed.
1496 AudioPatchCollection patchesToRemove = getMsdPatches();
1497 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1498 auto retainedPatch = false;
1499 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1500 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1501 patchesToRemove.removeItemsAt(i);
1502 retainedPatch = true;
1503 break;
1504 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001505 }
Michael Chan6fb34492020-12-08 15:44:49 +11001506 if (retainedPatch) {
1507 it = patchesToCreate.erase(it);
1508 continue;
1509 }
1510 ++it;
1511 }
1512 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1513 return NO_ERROR;
1514 }
1515 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1516 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001517 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001518 }
Michael Chan6fb34492020-12-08 15:44:49 +11001519 status_t status = NO_ERROR;
1520 for (const auto &p : patchesToCreate) {
1521 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1522 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1523 char message[256];
1524 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1525 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1526 currStatus == NO_ERROR ? "Success" : "Error",
1527 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1528 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1529 if (currStatus == NO_ERROR) {
1530 ALOGD("%s", message);
1531 } else {
1532 ALOGE("%s", message);
1533 if (status == NO_ERROR) {
1534 status = currStatus;
1535 }
1536 }
1537 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001538 return status;
1539}
1540
Michael Chan6fb34492020-12-08 15:44:49 +11001541void AudioPolicyManager::releaseMsdPatches(const DeviceVector& devices) {
1542 AudioPatchCollection msdPatches = getMsdPatches();
1543 for (size_t i = 0; i < msdPatches.size(); i++) {
1544 const auto& patch = msdPatches[i];
1545 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1546 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1547 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1548 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1549 releaseAudioPatch(patch->getHandle(), mUidCached);
1550 break;
1551 }
1552 }
1553 }
1554}
1555
Eric Laurente0720872014-03-11 09:30:41 -07001556audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001557 audio_output_flags_t flags,
1558 audio_format_t format,
1559 audio_channel_mask_t channelMask,
1560 uint32_t samplingRate,
1561 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001562{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001563 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1564 "%s called with format %#x", __func__, format);
1565
jiabinebb6af42020-06-09 17:31:17 -07001566 // Return the output that haptic-generating attached to when 1) session id is specified,
1567 // 2) haptic-generating effect exists for given session id and 3) the output that
1568 // haptic-generating effect attached to is in given outputs.
1569 if (sessionId != AUDIO_SESSION_NONE) {
1570 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1571 sessionId, FX_IID_HAPTICGENERATOR);
1572 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1573 return hapticGeneratingOutput;
1574 }
1575 }
1576
Eric Laurent16c66dd2019-05-01 17:54:10 -07001577 // Flags disqualifying an output: the match must happen before calling selectOutput()
1578 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1579 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1580
1581 // Flags expressing a functional request: must be honored in priority over
1582 // other criteria
1583 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1584 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1585 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1586 // Flags expressing a performance request: have lower priority than serving
1587 // requested sampling rate or channel mask
1588 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1589 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1590 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1591
1592 const audio_output_flags_t functionalFlags =
1593 (audio_output_flags_t)(flags & kFunctionalFlags);
1594 const audio_output_flags_t performanceFlags =
1595 (audio_output_flags_t)(flags & kPerformanceFlags);
1596
1597 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1598
Eric Laurente552edb2014-03-10 17:42:56 -07001599 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001600 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001601 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001602 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001603 // 2: the output with the highest number of requested functional flags
1604 // 3: the output supporting the exact channel mask
1605 // 4: the output with a higher channel count than requested
1606 // 5: the output with a higher sampling rate than requested
1607 // 6: the output with the highest number of requested performance flags
1608 // 7: the output with the bit depth the closest to the requested one
1609 // 8: the primary output
1610 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001611
Eric Laurent16c66dd2019-05-01 17:54:10 -07001612 // matching criteria values in priority order for best matching output so far
1613 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001614
Eric Laurent16c66dd2019-05-01 17:54:10 -07001615 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1616 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1617 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001618
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001619 for (audio_io_handle_t output : outputs) {
1620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001621 // matching criteria values in priority order for current output
1622 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001623
Eric Laurent16c66dd2019-05-01 17:54:10 -07001624 if (outputDesc->isDuplicated()) {
1625 continue;
1626 }
1627 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1628 continue;
1629 }
Eric Laurent8838a382014-09-08 16:44:28 -07001630
Eric Laurent16c66dd2019-05-01 17:54:10 -07001631 // If haptic channel is specified, use the haptic output if present.
1632 // When using haptic output, same audio format and sample rate are required.
1633 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001634 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001635 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1636 continue;
1637 }
1638 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001639 && format == outputDesc->getFormat()
1640 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001641 currentMatchCriteria[0] = outputHapticChannelCount;
1642 }
1643
1644 // functional flags match
1645 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1646
1647 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001648 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1649 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001650 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1651 channelCount <= outputChannelCount) {
1652 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001653 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1654 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001655 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001656 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001657 currentMatchCriteria[3] = outputChannelCount;
1658 }
1659
1660 // sampling rate match
1661 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001662 samplingRate <= outputDesc->getSamplingRate()) {
1663 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001664 }
1665
1666 // performance flags match
1667 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1668
1669 // format match
1670 if (format != AUDIO_FORMAT_INVALID) {
1671 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001672 PolicyAudioPort::kFormatDistanceMax -
1673 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001674 }
1675
1676 // primary output match
1677 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1678
1679 // compare match criteria by priority then value
1680 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1681 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1682 bestMatchCriteria = currentMatchCriteria;
1683 bestOutput = output;
1684
1685 std::stringstream result;
1686 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1687 std::ostream_iterator<int>(result, " "));
1688 ALOGV("%s new bestOutput %d criteria %s",
1689 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001690 }
1691 }
1692
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001694}
1695
Eric Laurent8fc147b2018-07-22 19:13:55 -07001696status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001697{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001698 ALOGV("%s portId %d", __FUNCTION__, portId);
1699
1700 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1701 if (outputDesc == 0) {
1702 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return BAD_VALUE;
1704 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001705 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurent8fc147b2018-07-22 19:13:55 -07001707 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001708 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001709
Eric Laurent733ce942017-12-07 12:18:25 -08001710 status_t status = outputDesc->start();
1711 if (status != NO_ERROR) {
1712 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001713 }
1714
Eric Laurent97ac8712018-07-27 18:59:02 -07001715 uint32_t delayMs;
1716 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001717
1718 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001719 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001720 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001721 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001722 if (delayMs != 0) {
1723 usleep(delayMs * 1000);
1724 }
1725
1726 return status;
1727}
1728
Eric Laurent97ac8712018-07-27 18:59:02 -07001729status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1730 const sp<TrackClientDescriptor>& client,
1731 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001732{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001733 // cannot start playback of STREAM_TTS if any other output is being used
1734 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001735
1736 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001737 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001738 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001739 auto clientStrategy = client->strategy();
1740 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001741 if (stream == AUDIO_STREAM_TTS) {
1742 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001743 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001744 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001745 return INVALID_OPERATION;
1746 } else {
1747 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1748 }
1749 } else {
1750 // some playback other than beacon starts
1751 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1752 }
1753
Eric Laurent77305a62016-07-25 16:39:22 -07001754 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001755 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001756 bool force = !outputDesc->isActive() &&
1757 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001758
François Gaffie11d30102018-11-02 16:09:09 +01001759 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001760 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001761 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001762 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001763 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001764 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001765 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001766 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001767 } else {
1768 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001769 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001770 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1771 AUDIO_FORMAT_DEFAULT);
1772 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1773 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001774 }
1775
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001776 // requiresMuteCheck is false when we can bypass mute strategy.
1777 // It covers a common case when there is no materially active audio
1778 // and muting would result in unnecessary delay and dropped audio.
1779 const uint32_t outputLatencyMs = outputDesc->latency();
1780 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1781
Eric Laurente552edb2014-03-10 17:42:56 -07001782 // increment usage count for this stream on the requested output:
1783 // NOTE that the usage count is the same for duplicated output and hardware output which is
1784 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001785 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001786
1787 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001788 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1789 client->isPreferredDeviceForExclusiveUse()) {
1790 // Preferred device may be exclusive, use only if no other active clients on this output
1791 devices = DeviceVector(
1792 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1793 } else {
1794 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1795 }
François Gaffie11d30102018-11-02 16:09:09 +01001796 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001797 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001798 }
1799 }
Eric Laurente552edb2014-03-10 17:42:56 -07001800
François Gaffiec005e562018-11-06 15:04:49 +01001801 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001802 selectOutputForMusicEffects();
1803 }
1804
François Gaffie1c878552018-11-22 16:53:21 +01001805 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001806 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001807 if (devices.isEmpty()) {
1808 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001809 }
François Gaffiec005e562018-11-06 15:04:49 +01001810 bool shouldWait =
1811 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1812 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1813 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001814 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001815 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001816 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001817 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001818 // An output has a shared device if
1819 // - managed by the same hw module
1820 // - supports the currently selected device
1821 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001822 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001823
Eric Laurent77305a62016-07-25 16:39:22 -07001824 // force a device change if any other output is:
1825 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001826 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001827 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001828 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001829 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001830 // change the device currently selected by the other output.
1831 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001832 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001833 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001834 force = true;
1835 }
1836 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001837 // a notification so that audio focus effect can propagate, or that a mute/unmute
1838 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001839 const uint32_t latencyMs = desc->latency();
1840 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1841
1842 if (shouldWait && isActive && (waitMs < latencyMs)) {
1843 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001844 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001845
1846 // Require mute check if another output is on a shared device
1847 // and currently active to have proper drain and avoid pops.
1848 // Note restoring AudioTracks onto this output needs to invoke
1849 // a volume ramp if there is no mute.
1850 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001851 }
1852 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001853
1854 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001855 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001856
Eric Laurente552edb2014-03-10 17:42:56 -07001857 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001858 auto &curves = getVolumeCurves(client->attributes());
1859 checkAndSetVolume(curves, client->volumeSource(),
1860 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001861 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001862 outputDesc->devices().types(), 0 /*delay*/,
1863 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001864
1865 // update the outputs if starting an output with a stream that can affect notification
1866 // routing
1867 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001868
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001869 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001870 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001871 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1872 }
Eric Laurentdc462862016-07-19 12:29:53 -07001873
1874 if (waitMs > muteWaitMs) {
1875 *delayMs = waitMs - muteWaitMs;
1876 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001877
1878 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1879 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1880 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1881 // change occurs after the MixerThread starts and causes a stream volume
1882 // glitch.
1883 //
1884 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001885 }
Eric Laurentdc462862016-07-19 12:29:53 -07001886
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001887 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001888 mEngine->getForceUse(
1889 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001890 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001891 }
1892
Eric Laurent97ac8712018-07-27 18:59:02 -07001893 // Automatically enable the remote submix input when output is started on a re routing mix
1894 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001895 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1896 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001897 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1898 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1899 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001900 "remote-submix",
1901 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001902 }
1903
Eric Laurente552edb2014-03-10 17:42:56 -07001904 return NO_ERROR;
1905}
1906
Eric Laurent8fc147b2018-07-22 19:13:55 -07001907status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001909 ALOGV("%s portId %d", __FUNCTION__, portId);
1910
1911 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1912 if (outputDesc == 0) {
1913 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001914 return BAD_VALUE;
1915 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001916 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001917
Eric Laurent97ac8712018-07-27 18:59:02 -07001918 ALOGV("stopOutput() output %d, stream %d, session %d",
1919 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001920
Eric Laurent97ac8712018-07-27 18:59:02 -07001921 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001922
Eric Laurent733ce942017-12-07 12:18:25 -08001923 if (status == NO_ERROR ) {
1924 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001925 }
1926 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001927}
1928
Eric Laurent97ac8712018-07-27 18:59:02 -07001929status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1930 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001931{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001932 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001933 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001934 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001935
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001936 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1937
François Gaffie1c878552018-11-22 16:53:21 +01001938 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1939 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001940 // Automatically disable the remote submix input when output is stopped on a
1941 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001942 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001943 if (isSingleDeviceType(
1944 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001945 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001946 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1948 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001949 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001950 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001951 }
1952 }
1953 bool forceDeviceUpdate = false;
1954 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001955 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001956 forceDeviceUpdate = true;
1957 }
1958
Eric Laurente552edb2014-03-10 17:42:56 -07001959 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001960 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001961
Eric Laurente552edb2014-03-10 17:42:56 -07001962 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001963 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001964 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001965 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001966 // delay the device switch by twice the latency because stopOutput() is executed when
1967 // the track stop() command is received and at that time the audio track buffer can
1968 // still contain data that needs to be drained. The latency only covers the audio HAL
1969 // and kernel buffers. Also the latency does not always include additional delay in the
1970 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001971 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001972
1973 // force restoring the device selection on other active outputs if it differs from the
1974 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001975 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001976 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001978 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001979 desc->isActive() &&
1980 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001981 (newDevices != desc->devices())) {
1982 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1983 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001984
François Gaffie11d30102018-11-02 16:09:09 +01001985 setOutputDevices(desc, newDevices2, force, delayMs);
1986
Eric Laurent57de36c2016-09-28 16:59:11 -07001987 // re-apply device specific volume if not done by setOutputDevice()
1988 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001989 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001990 }
Eric Laurente552edb2014-03-10 17:42:56 -07001991 }
1992 }
1993 // update the outputs if stopping one with a stream that can affect notification routing
1994 handleNotificationRoutingForStream(stream);
1995 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001996
1997 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1998 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001999 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002000 }
2001
François Gaffiec005e562018-11-06 15:04:49 +01002002 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002003 selectOutputForMusicEffects();
2004 }
Eric Laurente552edb2014-03-10 17:42:56 -07002005 return NO_ERROR;
2006 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002007 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002008 return INVALID_OPERATION;
2009 }
2010}
2011
jiabinbce0c1d2020-10-05 11:20:18 -07002012bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002013{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002014 ALOGV("%s portId %d", __FUNCTION__, portId);
2015
2016 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2017 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002018 // If an output descriptor is closed due to a device routing change,
2019 // then there are race conditions with releaseOutput from tracks
2020 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2021 // destroyed shortly thereafter.
2022 //
2023 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002025 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002026 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002027
2028 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002029
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302030 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2031 if (outputDesc->isClientActive(client)) {
2032 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2033 stopOutput(portId);
2034 }
2035
Eric Laurent8fc147b2018-07-22 19:13:55 -07002036 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2037 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002038 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002039 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002040 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002041 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002042 if (--outputDesc->mDirectOpenCount == 0) {
2043 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002044 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002045 }
2046 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302047
Andy Hung39efb7a2018-09-26 15:39:28 -07002048 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002049 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2050 // The output is pending reopened to query dynamic profiles and
2051 // there is no active clients
2052 closeOutput(outputDesc->mIoHandle);
2053 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2054 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2055 if (newOutputDesc == nullptr) {
2056 ALOGE("%s failed to open output", __func__);
2057 }
2058 return true;
2059 }
2060 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002061}
2062
Eric Laurentcaf7f482014-11-25 17:50:47 -08002063status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2064 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002065 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002066 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002067 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002068 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002069 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002070 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002071 input_type_t *inputType,
2072 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002073{
François Gaffiec005e562018-11-06 15:04:49 +01002074 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2075 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2076 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002077
Eric Laurentad2e7b92017-09-14 20:06:42 -07002078 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002079 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002080 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002081 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002082 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002083 sp<AudioInputDescriptor> inputDesc;
2084 sp<RecordClientDescriptor> clientDesc;
2085 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002087
2088 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2089 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2090 return INVALID_OPERATION;
2091 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002092
Francois Gaffie716e1432019-01-14 16:58:59 +01002093 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2094 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002095 }
2096
Paul McLean466dc8e2015-04-17 13:15:36 -06002097 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002098 sp<DeviceDescriptor> explicitRoutingDevice =
2099 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002100
Eric Laurentad2e7b92017-09-14 20:06:42 -07002101 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2102 // possible
2103 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2104 *input != AUDIO_IO_HANDLE_NONE) {
2105 ssize_t index = mInputs.indexOfKey(*input);
2106 if (index < 0) {
2107 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2108 status = BAD_VALUE;
2109 goto error;
2110 }
2111 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112 RecordClientVector clients = inputDesc->getClientsForSession(session);
2113 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002114 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2115 status = BAD_VALUE;
2116 goto error;
2117 }
2118 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2119 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002120 // corresponds to a new client and is only permitted from the same UID.
2121 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 if (clients.size() > 1) {
2123 for (const auto& client : clients) {
2124 // The client map is ordered by key values (portId) and portIds are allocated
2125 // incrementaly. So the first client in this list is the one opened by audio flinger
2126 // when the mmap stream is created and should be ignored as it does not correspond
2127 // to an actual client
2128 if (client == *clients.cbegin()) {
2129 continue;
2130 }
2131 if (uid != client->uid() && !client->isSilenced()) {
2132 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2133 uid, client->portId(), client->uid());
2134 status = INVALID_OPERATION;
2135 goto error;
2136 }
Eric Laurent331679c2018-04-16 17:03:16 -07002137 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002138 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002139 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002140 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002141
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002144 }
2145
2146 *input = AUDIO_IO_HANDLE_NONE;
2147 *inputType = API_INPUT_INVALID;
2148
Francois Gaffie716e1432019-01-14 16:58:59 +01002149 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002150
Francois Gaffie716e1432019-01-14 16:58:59 +01002151 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2152 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2153 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002154 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002155 ALOGW("%s could not find input mix for attr %s",
2156 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002157 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002158 }
jiabinc1de2df2019-05-07 14:26:40 -07002159 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2160 String8(attr->tags + strlen("addr=")),
2161 AUDIO_FORMAT_DEFAULT);
2162 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002163 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002164 __func__, attributes.source, attributes.tags);
2165 status = BAD_VALUE;
2166 goto error;
2167 }
2168
Kevin Rocard25f9b052019-02-27 15:08:54 -08002169 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2170 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2171 } else {
2172 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2173 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002174 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002175 if (explicitRoutingDevice != nullptr) {
2176 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002177 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002178 // Prevent from storing invalid requested device id in clients
2179 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002180 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002181 }
François Gaffie11d30102018-11-02 16:09:09 +01002182 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002183 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002184 status = BAD_VALUE;
2185 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002186 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002187 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002188 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2189 // there is an external policy, but this input is attached to a mix of recorders,
2190 // meaning it receives audio injected into the framework, so the recorder doesn't
2191 // know about it and is therefore considered "legacy"
2192 *inputType = API_INPUT_LEGACY;
2193 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002194 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002195 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002196 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002197 } else {
2198 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002199 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002200
Eric Laurent599c7582015-12-07 18:05:55 -08002201 }
2202
François Gaffiec005e562018-11-06 15:04:49 +01002203 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002204 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002205 status = INVALID_OPERATION;
2206 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002207 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002208
Eric Laurent8f42ea12018-08-08 09:08:25 -07002209exit:
2210
François Gaffiec005e562018-11-06 15:04:49 +01002211 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2212 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002213
Francois Gaffie716e1432019-01-14 16:58:59 +01002214 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002215 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002216 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002217
Mikhail Naganov2996f672019-04-18 12:29:59 -07002218 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002219 requestedDeviceId, attributes.source, flags,
2220 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002221 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002222 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002223
2224 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2225 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002226
Eric Laurent599c7582015-12-07 18:05:55 -08002227 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002228
2229error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002230 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002231}
2232
2233
François Gaffie11d30102018-11-02 16:09:09 +01002234audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002235 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002236 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002237 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002238 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002239 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002240{
2241 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002242 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002243 bool isSoundTrigger = false;
2244
François Gaffiec005e562018-11-06 15:04:49 +01002245 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002246 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2247 if (index >= 0) {
2248 input = mSoundTriggerSessions.valueFor(session);
2249 isSoundTrigger = true;
2250 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2251 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2252 } else {
2253 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002254 }
François Gaffiec005e562018-11-06 15:04:49 +01002255 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002256 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002257 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002258 }
2259
Andy Hungf129b032015-04-07 13:45:50 -07002260 // find a compatible input profile (not necessarily identical in parameters)
2261 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002262 // sampling rate and flags may be updated by getInputProfile
2263 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2264 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002265 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002266 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002267 audio_input_flags_t profileFlags = flags;
2268 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002269 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002270 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002271 profileFlags);
2272 if (profile != 0) {
2273 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002274 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2275 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002276 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2277 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2278 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002279 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2280 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2281 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002282 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002283 }
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002285 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002286 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002287 if (samplingRate == 0) {
2288 samplingRate = profileSamplingRate;
2289 }
Eric Laurente552edb2014-03-10 17:42:56 -07002290
Eric Laurent322b4d22015-04-03 15:57:54 -07002291 if (profile->getModuleHandle() == 0) {
2292 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002293 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002294 }
2295
Eric Laurent3974e3b2017-12-07 17:58:43 -08002296 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002297 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002298 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002299 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002300 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002301 continue;
2302 }
2303 // if sound trigger, reuse input if used by other sound trigger on same session
2304 // else
2305 // reuse input if active client app is not in IDLE state
2306 //
2307 RecordClientVector clients = desc->clientsList();
2308 bool doClose = false;
2309 for (const auto& client : clients) {
2310 if (isSoundTrigger != client->isSoundTrigger()) {
2311 continue;
2312 }
2313 if (client->isSoundTrigger()) {
2314 if (session == client->session()) {
2315 return desc->mIoHandle;
2316 }
2317 continue;
2318 }
2319 if (client->active() && client->appState() != APP_STATE_IDLE) {
2320 return desc->mIoHandle;
2321 }
2322 doClose = true;
2323 }
2324 if (doClose) {
2325 closeInput(desc->mIoHandle);
2326 } else {
2327 i++;
2328 }
2329 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002330 }
2331
Eric Laurentfe231122017-11-17 17:48:06 -08002332 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002333
Eric Laurentfe231122017-11-17 17:48:06 -08002334 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2335 lConfig.sample_rate = profileSamplingRate;
2336 lConfig.channel_mask = profileChannelMask;
2337 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002338
François Gaffie11d30102018-11-02 16:09:09 +01002339 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002340
2341 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002342 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002343 (profileSamplingRate != lConfig.sample_rate) ||
2344 !audio_formats_match(profileFormat, lConfig.format) ||
2345 (profileChannelMask != lConfig.channel_mask)) {
2346 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002347 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002348 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002349 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002350 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002351 }
Eric Laurent599c7582015-12-07 18:05:55 -08002352 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002353 }
2354
Eric Laurentc722f302014-12-10 11:21:49 -08002355 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002356
Eric Laurent599c7582015-12-07 18:05:55 -08002357 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002358 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002359
Eric Laurent599c7582015-12-07 18:05:55 -08002360 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002361}
2362
Eric Laurent4eb58f12018-12-07 16:41:02 -08002363status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002364{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002365 ALOGV("%s portId %d", __FUNCTION__, portId);
2366
2367 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2368 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002369 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002370 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002372 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002373 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002374 if (client->active()) {
2375 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2376 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002377 }
2378
Eric Laurent8f42ea12018-08-08 09:08:25 -07002379 audio_session_t session = client->session();
2380
Eric Laurent4eb58f12018-12-07 16:41:02 -08002381 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002382
Eric Laurent4eb58f12018-12-07 16:41:02 -08002383 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002384
Eric Laurent4eb58f12018-12-07 16:41:02 -08002385 status_t status = inputDesc->start();
2386 if (status != NO_ERROR) {
2387 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002388 }
Eric Laurente552edb2014-03-10 17:42:56 -07002389
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002390 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002391 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002392 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002393
Eric Laurent8f42ea12018-08-08 09:08:25 -07002394 // indicate active capture to sound trigger service if starting capture from a mic on
2395 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002396 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002397 if (device != nullptr) {
2398 status = setInputDevice(input, device, true /* force */);
2399 } else {
2400 ALOGW("%s no new input device can be found for descriptor %d",
2401 __FUNCTION__, inputDesc->getId());
2402 status = BAD_VALUE;
2403 }
Eric Laurente552edb2014-03-10 17:42:56 -07002404
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002405 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002406 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002407 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002408 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002409 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2410 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002411 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002412 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002413
François Gaffie11d30102018-11-02 16:09:09 +01002414 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2415 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002416 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002417 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002418 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002419
Eric Laurent8f42ea12018-08-08 09:08:25 -07002420 // automatically enable the remote submix output when input is started if not
2421 // used by a policy mix of type MIX_TYPE_RECORDERS
2422 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002423 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002424 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002425 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002426 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002427 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2428 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002429 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002430 if (address != "") {
2431 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2432 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002433 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002434 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002435 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002436 } else if (status != NO_ERROR) {
2437 // Restore client activity state.
2438 inputDesc->setClientActive(client, false);
2439 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002440 }
2441
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002442 ALOGV("%s input %d source = %d status = %d exit",
2443 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002444
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002445 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002446}
2447
Eric Laurent8fc147b2018-07-22 19:13:55 -07002448status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002449{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002450 ALOGV("%s portId %d", __FUNCTION__, portId);
2451
2452 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2453 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002454 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002455 return BAD_VALUE;
2456 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002458 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002459 if (!client->active()) {
2460 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002461 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002462 }
2463
Eric Laurent8f42ea12018-08-08 09:08:25 -07002464 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002465
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 inputDesc->stop();
2467 if (inputDesc->isActive()) {
2468 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2469 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002470 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002471 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002472 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002473 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2474 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002476 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002477
2478 // automatically disable the remote submix output when input is stopped if not
2479 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002480 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002482 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002483 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002484 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2485 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002486 }
2487 if (address != "") {
2488 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2489 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002490 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491 }
2492 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002493 resetInputDevice(input);
2494
2495 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2496 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002497 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2498 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002499 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002500 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 }
2502 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002503 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002504 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002505}
2506
Eric Laurent8fc147b2018-07-22 19:13:55 -07002507void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002508{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002509 ALOGV("%s portId %d", __FUNCTION__, portId);
2510
2511 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2512 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002513 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002514 return;
2515 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002516 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002517 audio_io_handle_t input = inputDesc->mIoHandle;
2518
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002520
Andy Hung39efb7a2018-09-26 15:39:28 -07002521 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002522
Andy Hung39efb7a2018-09-26 15:39:28 -07002523 if (inputDesc->getClientCount() > 0) {
2524 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002525 return;
2526 }
2527
Eric Laurent05b90f82014-08-27 15:32:29 -07002528 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002529 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002530 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002531}
2532
Eric Laurent8f42ea12018-08-08 09:08:25 -07002533void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002534{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002535 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002536
2537 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002538 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002539 }
2540}
2541
Eric Laurent8f42ea12018-08-08 09:08:25 -07002542void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2543{
2544 stopInput(portId);
2545 releaseInput(portId);
2546}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002547
Eric Laurent0dd51852019-04-19 18:18:58 -07002548void AudioPolicyManager::checkCloseInputs() {
2549 // After connecting or disconnecting an input device, close input if:
2550 // - it has no client (was just opened to check profile) OR
2551 // - none of its supported devices are connected anymore OR
2552 // - one of its clients cannot be routed to one of its supported
2553 // devices anymore. Otherwise update device selection
2554 std::vector<audio_io_handle_t> inputsToClose;
2555 for (size_t i = 0; i < mInputs.size(); i++) {
2556 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2557 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002558 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002559 inputsToClose.push_back(mInputs.keyAt(i));
2560 } else {
2561 bool close = false;
2562 for (const auto& client : input->clientsList()) {
2563 sp<DeviceDescriptor> device =
2564 mEngine->getInputDeviceForAttributes(client->attributes());
2565 if (!input->supportedDevices().contains(device)) {
2566 close = true;
2567 break;
2568 }
2569 }
2570 if (close) {
2571 inputsToClose.push_back(mInputs.keyAt(i));
2572 } else {
2573 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2574 }
2575 }
2576 }
2577
2578 for (const audio_io_handle_t handle : inputsToClose) {
2579 ALOGV("%s closing input %d", __func__, handle);
2580 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002581 }
Eric Laurentd4692962014-05-05 18:13:44 -07002582}
2583
François Gaffie251c7f02018-11-07 10:41:08 +01002584void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002585{
2586 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002587 if (indexMin < 0 || indexMax < 0) {
2588 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2589 return;
2590 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002591 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002592
2593 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002594 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2595 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002596 continue;
2597 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002598 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002599 }
Eric Laurente552edb2014-03-10 17:42:56 -07002600}
2601
Eric Laurente0720872014-03-11 09:30:41 -07002602status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002603 int index,
2604 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002605{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002606 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002607 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2608 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2609 return NO_ERROR;
2610 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002611 ALOGV("%s: stream %s attributes=%s", __func__,
2612 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002613 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002614}
2615
Eric Laurente0720872014-03-11 09:30:41 -07002616status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002617 int *index,
2618 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002619{
François Gaffiec005e562018-11-06 15:04:49 +01002620 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2621 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002622 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002623 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002624 deviceTypes = mEngine->getOutputDevicesForStream(
2625 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002626 }
jiabin9a3361e2019-10-01 09:38:30 -07002627 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002628}
2629
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002630status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002631 int index,
2632 audio_devices_t device)
2633{
2634 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002635 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2636 if (group == VOLUME_GROUP_NONE) {
2637 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002638 return BAD_VALUE;
2639 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002640 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002641 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002642 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002643 VolumeSource vs = toVolumeSource(group);
2644 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2645
2646 status = setVolumeCurveIndex(index, device, curves);
2647 if (status != NO_ERROR) {
2648 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2649 return status;
2650 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002651
jiabin9a3361e2019-10-01 09:38:30 -07002652 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002653 auto curCurvAttrs = curves.getAttributes();
2654 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2655 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002656 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002657 } else if (!curves.getStreamTypes().empty()) {
2658 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002659 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002660 } else {
2661 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2662 return BAD_VALUE;
2663 }
jiabin9a3361e2019-10-01 09:38:30 -07002664 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2665 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002666
François Gaffiecfe17322018-11-07 13:41:29 +01002667 // update volume on all outputs and streams matching the following:
2668 // - The requested stream (or a stream matching for volume control) is active on the output
2669 // - The device (or devices) selected by the engine for this stream includes
2670 // the requested device
2671 // - For non default requested device, currently selected device on the output is either the
2672 // requested device or one of the devices selected by the engine for this stream
2673 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2674 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002675 for (size_t i = 0; i < mOutputs.size(); i++) {
2676 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002677 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002678
jiabin9a3361e2019-10-01 09:38:30 -07002679 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2680 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002681 }
François Gaffieed91f582020-01-31 10:35:37 +01002682 if (!(desc->isActive(vs) || isInCall())) {
2683 continue;
2684 }
2685 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2686 curDevices.find(device) == curDevices.end()) {
2687 continue;
2688 }
2689 bool applyVolume = false;
2690 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2691 curSrcDevices.insert(device);
2692 applyVolume = (curSrcDevices.find(
2693 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2694 } else {
2695 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2696 }
2697 if (!applyVolume) {
2698 continue; // next output
2699 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002700 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2701 // If a higher priority strategy is active, and the output is routed to a device with a
2702 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002703 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002704 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002705 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2706 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2707 false /*preferredDevice*/);
2708 if (activeClients.empty()) {
2709 continue;
2710 }
2711 bool isPreempted = false;
2712 bool isHigherPriority = productStrategy < strategy;
2713 for (const auto &client : activeClients) {
2714 if (isHigherPriority && (client->volumeSource() != vs)) {
2715 ALOGV("%s: Strategy=%d (\nrequester:\n"
2716 " group %d, volumeGroup=%d attributes=%s)\n"
2717 " higher priority source active:\n"
2718 " volumeGroup=%d attributes=%s) \n"
2719 " on output %zu, bailing out", __func__, productStrategy,
2720 group, group, toString(attributes).c_str(),
2721 client->volumeSource(), toString(client->attributes()).c_str(), i);
2722 applyVolume = false;
2723 isPreempted = true;
2724 break;
2725 }
2726 // However, continue for loop to ensure no higher prio clients running on output
2727 if (client->volumeSource() == vs) {
2728 applyVolume = true;
2729 }
2730 }
2731 if (isPreempted || applyVolume) {
2732 break;
2733 }
2734 }
2735 if (!applyVolume) {
2736 continue; // next output
2737 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002738 }
François Gaffieed91f582020-01-31 10:35:37 +01002739 //FIXME: workaround for truncated touch sounds
2740 // delayed volume change for system stream to be removed when the problem is
2741 // handled by system UI
2742 status_t volStatus = checkAndSetVolume(
2743 curves, vs, index, desc, curDevices,
2744 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2745 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2746 if (volStatus != NO_ERROR) {
2747 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002748 }
2749 }
François Gaffiecfe17322018-11-07 13:41:29 +01002750 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2751 return status;
2752}
2753
François Gaffieaaac0fd2018-11-22 17:56:39 +01002754status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002755 audio_devices_t device,
2756 IVolumeCurves &volumeCurves)
2757{
2758 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2759 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002760 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2761 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002762 (index > volumeCurves.getVolumeIndexMax())) {
2763 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2764 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2765 return BAD_VALUE;
2766 }
2767 if (!audio_is_output_device(device)) {
2768 return BAD_VALUE;
2769 }
2770
2771 // Force max volume if stream cannot be muted
2772 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2773
François Gaffieaaac0fd2018-11-22 17:56:39 +01002774 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002775 volumeCurves.addCurrentVolumeIndex(device, index);
2776 return NO_ERROR;
2777}
2778
2779status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2780 int &index,
2781 audio_devices_t device)
2782{
2783 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2784 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002785 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002786 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002787 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2788 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002789 }
jiabin9a3361e2019-10-01 09:38:30 -07002790 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002791}
2792
2793status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2794 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002795 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002796{
jiabin9a3361e2019-10-01 09:38:30 -07002797 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002798 return BAD_VALUE;
2799 }
jiabin9a3361e2019-10-01 09:38:30 -07002800 index = curves.getVolumeIndex(deviceTypes);
2801 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002802 return NO_ERROR;
2803}
2804
2805status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2806 int &index)
2807{
2808 index = getVolumeCurves(attr).getVolumeIndexMin();
2809 return NO_ERROR;
2810}
2811
2812status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2813 int &index)
2814{
2815 index = getVolumeCurves(attr).getVolumeIndexMax();
2816 return NO_ERROR;
2817}
2818
Eric Laurent36829f92017-04-07 19:04:42 -07002819audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002820{
2821 // select one output among several suitable for global effects.
2822 // The priority is as follows:
2823 // 1: An offloaded output. If the effect ends up not being offloadable,
2824 // AudioFlinger will invalidate the track and the offloaded output
2825 // will be closed causing the effect to be moved to a PCM output.
2826 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002827 // 3: The primary output
2828 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002829
François Gaffiec005e562018-11-06 15:04:49 +01002830 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2831 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002832 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002833
Eric Laurent36829f92017-04-07 19:04:42 -07002834 if (outputs.size() == 0) {
2835 return AUDIO_IO_HANDLE_NONE;
2836 }
Eric Laurente552edb2014-03-10 17:42:56 -07002837
Eric Laurent36829f92017-04-07 19:04:42 -07002838 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2839 bool activeOnly = true;
2840
2841 while (output == AUDIO_IO_HANDLE_NONE) {
2842 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2843 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2844 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2845
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002846 for (audio_io_handle_t output : outputs) {
2847 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002848 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002849 continue;
2850 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002851 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2852 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002853 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002854 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002855 }
2856 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002857 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002858 }
2859 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002860 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002861 }
2862 }
2863 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2864 output = outputOffloaded;
2865 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2866 output = outputDeepBuffer;
2867 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2868 output = outputPrimary;
2869 } else {
2870 output = outputs[0];
2871 }
2872 activeOnly = false;
2873 }
2874
2875 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002876 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002877 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2878 mMusicEffectOutput = output;
2879 }
2880
2881 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002882 return output;
2883}
2884
Eric Laurent36829f92017-04-07 19:04:42 -07002885audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2886{
2887 return selectOutputForMusicEffects();
2888}
2889
Eric Laurente0720872014-03-11 09:30:41 -07002890status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002891 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002892 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002893 int session,
2894 int id)
2895{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002896 if (session != AUDIO_SESSION_DEVICE) {
2897 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002898 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002899 index = mInputs.indexOfKey(io);
2900 if (index < 0) {
2901 ALOGW("registerEffect() unknown io %d", io);
2902 return INVALID_OPERATION;
2903 }
Eric Laurente552edb2014-03-10 17:42:56 -07002904 }
2905 }
François Gaffiec005e562018-11-06 15:04:49 +01002906 return mEffects.registerEffect(desc, io, session, id,
2907 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2908 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002909}
2910
Eric Laurentc241b0d2018-11-28 09:08:49 -08002911status_t AudioPolicyManager::unregisterEffect(int id)
2912{
2913 if (mEffects.getEffect(id) == nullptr) {
2914 return INVALID_OPERATION;
2915 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002916 if (mEffects.isEffectEnabled(id)) {
2917 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2918 setEffectEnabled(id, false);
2919 }
2920 return mEffects.unregisterEffect(id);
2921}
2922
2923status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2924{
2925 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2926 if (effect == nullptr) {
2927 return INVALID_OPERATION;
2928 }
2929
2930 status_t status = mEffects.setEffectEnabled(id, enabled);
2931 if (status == NO_ERROR) {
2932 mInputs.trackEffectEnabled(effect, enabled);
2933 }
2934 return status;
2935}
2936
Eric Laurent6c796322019-04-09 14:13:17 -07002937
2938status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2939{
2940 mEffects.moveEffects(ids, io);
2941 return NO_ERROR;
2942}
2943
Eric Laurentc75307b2015-03-17 15:29:32 -07002944bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2945{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002946 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002947}
2948
2949bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2950{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002951 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002952}
2953
Eric Laurente0720872014-03-11 09:30:41 -07002954bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002955{
2956 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002957 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002958 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002959 return true;
2960 }
2961 }
2962 return false;
2963}
2964
Eric Laurent275e8e92014-11-30 15:14:47 -08002965// Register a list of custom mixes with their attributes and format.
2966// When a mix is registered, corresponding input and output profiles are
2967// added to the remote submix hw module. The profile contains only the
2968// parameters (sampling rate, format...) specified by the mix.
2969// The corresponding input remote submix device is also connected.
2970//
2971// When a remote submix device is connected, the address is checked to select the
2972// appropriate profile and the corresponding input or output stream is opened.
2973//
2974// When capture starts, getInputForAttr() will:
2975// - 1 look for a mix matching the address passed in attribtutes tags if any
2976// - 2 if none found, getDeviceForInputSource() will:
2977// - 2.1 look for a mix matching the attributes source
2978// - 2.2 if none found, default to device selection by policy rules
2979// At this time, the corresponding output remote submix device is also connected
2980// and active playback use cases can be transferred to this mix if needed when reconnecting
2981// after AudioTracks are invalidated
2982//
2983// When playback starts, getOutputForAttr() will:
2984// - 1 look for a mix matching the address passed in attribtutes tags if any
2985// - 2 if none found, look for a mix matching the attributes usage
2986// - 3 if none found, default to device and output selection by policy rules.
2987
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002988status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002989{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002990 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2991 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002992 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002993 sp<HwModule> rSubmixModule;
2994 // examine each mix's route type
2995 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002996 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002997 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2998 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2999 ALOGE("Unsupported Policy Mix %zu of %zu: "
3000 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3001 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003002 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003003 break;
3004 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003005 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3006 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003007 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003008 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3009 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003010 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003011 rSubmixModule = mHwModules.getModuleFromName(
3012 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3013 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003014 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003015 i);
3016 res = INVALID_OPERATION;
3017 break;
3018 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003019 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003020
Eric Laurent97ac8712018-07-27 18:59:02 -07003021 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003022 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003023 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003024 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003025 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3026 } else {
3027 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3028 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003029 }
François Gaffie036e1e92015-03-19 10:16:24 +01003030
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003031 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003032 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003033 res = INVALID_OPERATION;
3034 break;
3035 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003036 audio_config_t outputConfig = mix.mFormat;
3037 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003038 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3039 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003040 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3041 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003042 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003043 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003044 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003045 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003046
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003047 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003048 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3049 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3050 ALOGE("Failed to set remote submix device available, type %u, address %s",
3051 mix.mDeviceType, address.string());
3052 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003053 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003054 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3055 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003056 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003057 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003058 i, mixes.size(), type, address.string());
3059
3060 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3061 mix.mDeviceType, mix.mDeviceAddress,
3062 String8(), AUDIO_FORMAT_DEFAULT);
3063 if (device == nullptr) {
3064 res = INVALID_OPERATION;
3065 break;
3066 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003067
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003068 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003069 // First try to find an already opened output supporting the device
3070 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003071 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003072
Eric Laurentc529cf62020-04-17 18:19:10 -07003073 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003074 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003075 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3076 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003077 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003078 } else {
3079 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003080 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003081 }
3082 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003083 // If no output found, try to find a direct output profile supporting the device
3084 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3085 sp<HwModule> module = mHwModules[i];
3086 for (size_t j = 0;
3087 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3088 j++) {
3089 sp<IOProfile> profile = module->getOutputProfiles()[j];
3090 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3091 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3092 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3093 address.string());
3094 res = INVALID_OPERATION;
3095 } else {
3096 foundOutput = true;
3097 }
3098 }
3099 }
3100 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003101 if (res != NO_ERROR) {
3102 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003103 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003104 res = INVALID_OPERATION;
3105 break;
3106 } else if (!foundOutput) {
3107 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003108 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003109 res = INVALID_OPERATION;
3110 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003111 } else {
3112 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003113 }
Eric Laurentc722f302014-12-10 11:21:49 -08003114 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003115 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003116 if (res != NO_ERROR) {
3117 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003118 } else if (checkOutputs) {
3119 checkForDeviceAndOutputChanges();
3120 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003121 }
3122 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003123}
3124
3125status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3126{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003127 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003129 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003130 sp<HwModule> rSubmixModule;
3131 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003132 for (const auto& mix : mixes) {
3133 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003134
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003135 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003136 rSubmixModule = mHwModules.getModuleFromName(
3137 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3138 if (rSubmixModule == 0) {
3139 res = INVALID_OPERATION;
3140 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003141 }
3142 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003143
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003144 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003145
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003146 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003147 res = INVALID_OPERATION;
3148 continue;
3149 }
3150
Kevin Rocard04ed0462019-05-02 17:53:24 -07003151 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3152 if (getDeviceConnectionState(device, address.string()) ==
3153 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3154 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3155 address.string(), "remote-submix",
3156 AUDIO_FORMAT_DEFAULT);
3157 if (res != OK) {
3158 ALOGE("Error making RemoteSubmix device unavailable for mix "
3159 "with type %d, address %s", device, address.string());
3160 }
3161 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003162 }
jiabin5740f082019-08-19 15:08:30 -07003163 rSubmixModule->removeOutputProfile(address.c_str());
3164 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003165
Kevin Rocard153f92d2018-12-18 18:33:28 -08003166 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003167 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003168 res = INVALID_OPERATION;
3169 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003170 } else {
3171 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003172 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003173 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003174 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003175 if (res == NO_ERROR && checkOutputs) {
3176 checkForDeviceAndOutputChanges();
3177 updateCallAndOutputRouting();
3178 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003179 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003180}
3181
Mikhail Naganov100f0122018-11-29 11:22:16 -08003182void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3183{
3184 size_t i = 0;
3185 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3186 for (const auto& fmt : mManualSurroundFormats) {
3187 if (i++ != 0) dst->append(", ");
3188 std::string sfmt;
3189 FormatConverter::toString(fmt, sfmt);
3190 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3191 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3192 }
3193}
3194
Eric Laurentc529cf62020-04-17 18:19:10 -07003195// Returns true if all devices types match the predicate and are supported by one HW module
3196bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003197 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003198 std::function<bool(audio_devices_t)> predicate,
3199 const char *context) {
3200 for (size_t i = 0; i < devices.size(); i++) {
3201 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003202 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003203 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003204 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003205 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003206 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003207 return false;
3208 }
3209 }
3210 return true;
3211}
3212
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003213status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003214 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003215 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003216 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3217 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003218 }
3219 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003220 if (res != NO_ERROR) {
3221 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3222 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003223 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003224
3225 checkForDeviceAndOutputChanges();
3226 updateCallAndOutputRouting();
3227
3228 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003229}
3230
3231status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3232 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003233 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3234 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003235 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003236 __FUNCTION__, uid);
3237 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003238 }
3239
Eric Laurentc529cf62020-04-17 18:19:10 -07003240 checkForDeviceAndOutputChanges();
3241 updateCallAndOutputRouting();
3242
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003243 return res;
3244}
3245
Eric Laurent2517af32020-11-25 15:31:27 +01003246
jiabin0a488932020-08-07 17:32:40 -07003247status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3248 device_role_t role,
3249 const AudioDeviceTypeAddrVector &devices) {
3250 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3251 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003252
Eric Laurentc529cf62020-04-17 18:19:10 -07003253 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003254 return BAD_VALUE;
3255 }
jiabin0a488932020-08-07 17:32:40 -07003256 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003257 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003258 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3259 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003260 return status;
3261 }
3262
3263 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003264
3265 bool forceVolumeReeval = false;
3266 // FIXME: workaround for truncated touch sounds
3267 // to be removed when the problem is handled by system UI
3268 uint32_t delayMs = 0;
3269 if (strategy == mCommunnicationStrategy) {
3270 forceVolumeReeval = true;
3271 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3272 updateInputRouting();
3273 }
3274 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003275
3276 return NO_ERROR;
3277}
3278
3279void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3280{
3281 uint32_t waitMs = 0;
3282 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3283 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3284 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003285 // Only apply special touch sound delay once
3286 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003287 }
3288 for (size_t i = 0; i < mOutputs.size(); i++) {
3289 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3290 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3291 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3292 // As done in setDeviceConnectionState, we could also fix default device issue by
3293 // preventing the force re-routing in case of default dev that distinguishes on address.
3294 // Let's give back to engine full device choice decision however.
3295 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003296 // Only apply special touch sound delay once
3297 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003298 }
3299 if (forceVolumeReeval && !newDevices.isEmpty()) {
3300 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3301 }
3302 }
3303}
3304
Eric Laurent2517af32020-11-25 15:31:27 +01003305void AudioPolicyManager::updateInputRouting() {
3306 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3307 auto newDevice = getNewInputDevice(activeDesc);
3308 // Force new input selection if the new device can not be reached via current input
3309 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3310 setInputDevice(activeDesc->mIoHandle, newDevice);
3311 } else {
3312 closeInput(activeDesc->mIoHandle);
3313 }
3314 }
3315}
3316
jiabin0a488932020-08-07 17:32:40 -07003317status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3318 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003319{
jiabin0a488932020-08-07 17:32:40 -07003320 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003321
jiabin0a488932020-08-07 17:32:40 -07003322 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003323 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003324 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3325 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003326 return status;
3327 }
3328
3329 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003330
3331 bool forceVolumeReeval = false;
3332 // FIXME: workaround for truncated touch sounds
3333 // to be removed when the problem is handled by system UI
3334 uint32_t delayMs = 0;
3335 if (strategy == mCommunnicationStrategy) {
3336 forceVolumeReeval = true;
3337 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3338 updateInputRouting();
3339 }
3340 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003341
3342 return NO_ERROR;
3343}
3344
jiabin0a488932020-08-07 17:32:40 -07003345status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3346 device_role_t role,
3347 AudioDeviceTypeAddrVector &devices) {
3348 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003349}
3350
Jiabin Huang3b98d322020-09-03 17:54:16 +00003351status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3352 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3353 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3354 dumpAudioDeviceTypeAddrVector(devices).c_str());
3355
Mikhail Naganov55773032020-10-01 15:08:13 -07003356 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003357 return BAD_VALUE;
3358 }
3359 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3360 ALOGW_IF(status != NO_ERROR,
3361 "Engine could not set preferred devices %s for audio source %d role %d",
3362 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3363
3364 return status;
3365}
3366
3367status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3368 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3369 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3370 dumpAudioDeviceTypeAddrVector(devices).c_str());
3371
Mikhail Naganov55773032020-10-01 15:08:13 -07003372 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003373 return BAD_VALUE;
3374 }
3375 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3376 ALOGW_IF(status != NO_ERROR,
3377 "Engine could not add preferred devices %s for audio source %d role %d",
3378 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3379
Eric Laurent2517af32020-11-25 15:31:27 +01003380 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003381 return status;
3382}
3383
3384status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3385 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3386{
3387 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3388 dumpAudioDeviceTypeAddrVector(devices).c_str());
3389
Mikhail Naganov55773032020-10-01 15:08:13 -07003390 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003391 return BAD_VALUE;
3392 }
3393
3394 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3395 audioSource, role, devices);
3396 ALOGW_IF(status != NO_ERROR,
3397 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3398
Eric Laurent2517af32020-11-25 15:31:27 +01003399 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003400 return status;
3401}
3402
3403status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3404 device_role_t role) {
3405 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3406
3407 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3408 ALOGW_IF(status != NO_ERROR,
3409 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3410
Eric Laurent2517af32020-11-25 15:31:27 +01003411 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003412 return status;
3413}
3414
3415status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3416 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3417 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3418}
3419
Oscar Azucena90e77632019-11-27 17:12:28 -08003420status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003421 const AudioDeviceTypeAddrVector& devices) {
3422 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003423 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3424 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003425 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003426 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3427 if (status != NO_ERROR) {
3428 ALOGE("%s() could not set device affinity for userId %d",
3429 __FUNCTION__, userId);
3430 return status;
3431 }
3432
3433 // reevaluate outputs for all devices
3434 checkForDeviceAndOutputChanges();
3435 updateCallAndOutputRouting();
3436
3437 return NO_ERROR;
3438}
3439
3440status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3441 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3442 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3443 if (status != NO_ERROR) {
3444 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3445 __FUNCTION__, userId);
3446 return status;
3447 }
3448
3449 // reevaluate outputs for all devices
3450 checkForDeviceAndOutputChanges();
3451 updateCallAndOutputRouting();
3452
3453 return NO_ERROR;
3454}
3455
Andy Hungc29d82b2018-10-05 12:23:17 -07003456void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003457{
Andy Hungc29d82b2018-10-05 12:23:17 -07003458 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3459 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003460 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003461 std::string stateLiteral;
3462 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003463 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003464 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3465 "communications", "media", "record", "dock", "system",
3466 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3467 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3468 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003469 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3470 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3471 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3472 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3473 dst->append(" (MANUAL: ");
3474 dumpManualSurroundFormats(dst);
3475 dst->append(")");
3476 }
3477 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003478 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003479 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3480 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003481 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003482 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003483
Andy Hungc29d82b2018-10-05 12:23:17 -07003484 mAvailableOutputDevices.dump(dst, String8("Available output"));
3485 mAvailableInputDevices.dump(dst, String8("Available input"));
3486 mHwModulesAll.dump(dst);
3487 mOutputs.dump(dst);
3488 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003489 mEffects.dump(dst);
3490 mAudioPatches.dump(dst);
3491 mPolicyMixes.dump(dst);
3492 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003493
Kevin Rocardb99cc752019-03-21 20:52:24 -07003494 dst->appendFormat(" AllowedCapturePolicies:\n");
3495 for (auto& policy : mAllowedCapturePolicies) {
3496 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3497 }
3498
François Gaffiec005e562018-11-06 15:04:49 +01003499 dst->appendFormat("\nPolicy Engine dump:\n");
3500 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003501}
3502
3503status_t AudioPolicyManager::dump(int fd)
3504{
3505 String8 result;
3506 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003507 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003508 return NO_ERROR;
3509}
3510
Kevin Rocardb99cc752019-03-21 20:52:24 -07003511status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3512{
3513 mAllowedCapturePolicies[uid] = capturePolicy;
3514 return NO_ERROR;
3515}
3516
Eric Laurente552edb2014-03-10 17:42:56 -07003517// This function checks for the parameters which can be offloaded.
3518// This can be enhanced depending on the capability of the DSP and policy
3519// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003520audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003521{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003522 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003523 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003524 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003525 offloadInfo.format,
3526 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3527 offloadInfo.has_video);
3528
Andy Hung2ddee192015-12-18 17:34:44 -08003529 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003530 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003531 }
3532
Eric Laurente552edb2014-03-10 17:42:56 -07003533 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003534 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003535 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3536 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003537 }
3538
3539 // Check if stream type is music, then only allow offload as of now.
3540 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3541 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003542 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3543 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003544 }
3545
3546 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003547 const bool allowOffloadWithVideo =
3548 property_get_bool("audio.offload.video", false /* default_value */);
3549 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003550 ALOGV("%s: has_video == true, returning false", __func__);
3551 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003552 }
3553
3554 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003555 const int min_duration_secs = property_get_int32(
3556 "audio.offload.min.duration.secs", -1 /* default_value */);
3557 if (min_duration_secs >= 0) {
3558 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003559 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3560 __func__, min_duration_secs);
3561 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003562 }
3563 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003564 ALOGV("%s: Offload denied by duration < default min(=%u)",
3565 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3566 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003567 }
3568
3569 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3570 // creating an offloaded track and tearing it down immediately after start when audioflinger
3571 // detects there is an active non offloadable effect.
3572 // FIXME: We should check the audio session here but we do not have it in this context.
3573 // This may prevent offloading in rare situations where effects are left active by apps
3574 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003575 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003576 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003577 }
3578
3579 // See if there is a profile to support this.
3580 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003581 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003582 offloadInfo.sample_rate,
3583 offloadInfo.format,
3584 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003585 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3586 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003587 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3588 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3589 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003590 if (profile == nullptr) {
3591 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3592 }
3593 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3594 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3595 }
3596 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003597}
3598
Michael Chana94fbb22018-04-24 14:31:19 +10003599bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3600 const audio_attributes_t& attributes) {
3601 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003602 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003603 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003604 config.sample_rate,
3605 config.format,
3606 config.channel_mask,
3607 output_flags,
3608 true /* directOnly */);
3609 ALOGV("%s() profile %sfound with name: %s, "
3610 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3611 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003612 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003613 config.sample_rate, config.format, config.channel_mask, output_flags);
3614 return (profile != 0);
3615}
3616
Eric Laurent6a94d692014-05-20 11:18:06 -07003617status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3618 audio_port_type_t type,
3619 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003620 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003621 unsigned int *generation)
3622{
jiabin19cdba52020-11-24 11:28:58 -08003623 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3624 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003625 return BAD_VALUE;
3626 }
3627 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003628 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003629 *num_ports = 0;
3630 }
3631
3632 size_t portsWritten = 0;
3633 size_t portsMax = *num_ports;
3634 *num_ports = 0;
3635 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003636 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3637 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003638 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003639 for (const auto& dev : mAvailableOutputDevices) {
3640 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003641 continue;
3642 }
3643 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003644 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003645 }
3646 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003647 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003648 }
3649 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003650 for (const auto& dev : mAvailableInputDevices) {
3651 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003652 continue;
3653 }
3654 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003655 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003656 }
3657 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003658 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003659 }
3660 }
3661 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3662 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3663 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3664 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3665 }
3666 *num_ports += mInputs.size();
3667 }
3668 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003669 size_t numOutputs = 0;
3670 for (size_t i = 0; i < mOutputs.size(); i++) {
3671 if (!mOutputs[i]->isDuplicated()) {
3672 numOutputs++;
3673 if (portsWritten < portsMax) {
3674 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3675 }
3676 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003677 }
Eric Laurent84c70242014-06-23 08:46:27 -07003678 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003679 }
3680 }
3681 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003682 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003683 return NO_ERROR;
3684}
3685
jiabin19cdba52020-11-24 11:28:58 -08003686status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003687{
Eric Laurent99fcae42018-05-17 16:59:18 -07003688 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3689 return BAD_VALUE;
3690 }
3691 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3692 if (dev != 0) {
3693 dev->toAudioPort(port);
3694 return NO_ERROR;
3695 }
3696 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3697 if (dev != 0) {
3698 dev->toAudioPort(port);
3699 return NO_ERROR;
3700 }
3701 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3702 if (out != 0) {
3703 out->toAudioPort(port);
3704 return NO_ERROR;
3705 }
3706 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3707 if (in != 0) {
3708 in->toAudioPort(port);
3709 return NO_ERROR;
3710 }
3711 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003712}
3713
François Gaffieafd4cea2019-11-18 15:50:22 +01003714status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3715 audio_patch_handle_t *handle,
3716 uid_t uid, uint32_t delayMs,
3717 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003718{
François Gaffieafd4cea2019-11-18 15:50:22 +01003719 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 if (handle == NULL || patch == NULL) {
3721 return BAD_VALUE;
3722 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003723 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003724
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003725 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003726 return BAD_VALUE;
3727 }
3728 // only one source per audio patch supported for now
3729 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003730 return INVALID_OPERATION;
3731 }
Eric Laurent874c42872014-08-08 15:13:39 -07003732
3733 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003734 return INVALID_OPERATION;
3735 }
Eric Laurent874c42872014-08-08 15:13:39 -07003736 for (size_t i = 0; i < patch->num_sinks; i++) {
3737 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3738 return INVALID_OPERATION;
3739 }
3740 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003741
3742 sp<AudioPatch> patchDesc;
3743 ssize_t index = mAudioPatches.indexOfKey(*handle);
3744
François Gaffieafd4cea2019-11-18 15:50:22 +01003745 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3746 patch->sources[0].role,
3747 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003748#if LOG_NDEBUG == 0
3749 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003750 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3751 patch->sinks[i].role,
3752 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003753 }
3754#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003755
3756 if (index >= 0) {
3757 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003758 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3759 __func__, mUidCached, patchDesc->getUid(), uid);
3760 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 return INVALID_OPERATION;
3762 }
3763 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003764 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 }
3766
3767 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003768 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003769 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003770 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003771 return BAD_VALUE;
3772 }
Eric Laurent84c70242014-06-23 08:46:27 -07003773 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3774 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003775 if (patchDesc != 0) {
3776 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003777 ALOGV("%s source id differs for patch current id %d new id %d",
3778 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003779 return BAD_VALUE;
3780 }
3781 }
Eric Laurent874c42872014-08-08 15:13:39 -07003782 DeviceVector devices;
3783 for (size_t i = 0; i < patch->num_sinks; i++) {
3784 // Only support mix to devices connection
3785 // TODO add support for mix to mix connection
3786 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003787 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003788 return INVALID_OPERATION;
3789 }
3790 sp<DeviceDescriptor> devDesc =
3791 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3792 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003793 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003794 return BAD_VALUE;
3795 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003796
François Gaffie11d30102018-11-02 16:09:09 +01003797 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003798 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003799 NULL, // updatedSamplingRate
3800 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003801 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003802 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003803 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003804 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003805 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003806 return INVALID_OPERATION;
3807 }
3808 devices.add(devDesc);
3809 }
3810 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003811 return INVALID_OPERATION;
3812 }
Eric Laurent874c42872014-08-08 15:13:39 -07003813
Eric Laurent6a94d692014-05-20 11:18:06 -07003814 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003815 ALOGV("%s setting device %s on output %d",
3816 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003817 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003818 index = mAudioPatches.indexOfKey(*handle);
3819 if (index >= 0) {
3820 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003821 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003822 }
3823 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003824 patchDesc->setUid(uid);
3825 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003827 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003828 return INVALID_OPERATION;
3829 }
3830 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3831 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3832 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003833 // only one sink supported when connecting an input device to a mix
3834 if (patch->num_sinks > 1) {
3835 return INVALID_OPERATION;
3836 }
François Gaffie53615e22015-03-19 09:24:12 +01003837 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 if (inputDesc == NULL) {
3839 return BAD_VALUE;
3840 }
3841 if (patchDesc != 0) {
3842 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3843 return BAD_VALUE;
3844 }
3845 }
François Gaffie11d30102018-11-02 16:09:09 +01003846 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003847 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003848 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003849 return BAD_VALUE;
3850 }
3851
François Gaffie11d30102018-11-02 16:09:09 +01003852 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003853 patch->sinks[0].sample_rate,
3854 NULL, /*updatedSampleRate*/
3855 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003856 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003857 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003858 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003859 // FIXME for the parameter type,
3860 // and the NONE
3861 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003862 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003863 return INVALID_OPERATION;
3864 }
3865 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003866 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003867 device->toString().c_str(), inputDesc->mIoHandle);
3868 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003869 index = mAudioPatches.indexOfKey(*handle);
3870 if (index >= 0) {
3871 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003872 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003873 }
3874 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003875 patchDesc->setUid(uid);
3876 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003877 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003878 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003879 return INVALID_OPERATION;
3880 }
3881 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3882 // device to device connection
3883 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003884 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003885 return BAD_VALUE;
3886 }
3887 }
François Gaffie11d30102018-11-02 16:09:09 +01003888 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003890 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003891 return BAD_VALUE;
3892 }
Eric Laurent874c42872014-08-08 15:13:39 -07003893
Eric Laurent6a94d692014-05-20 11:18:06 -07003894 //update source and sink with our own data as the data passed in the patch may
3895 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003896 PatchBuilder patchBuilder;
3897 audio_port_config sourcePortConfig = {};
3898 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3899 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003900
Eric Laurent874c42872014-08-08 15:13:39 -07003901 for (size_t i = 0; i < patch->num_sinks; i++) {
3902 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003903 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003904 return INVALID_OPERATION;
3905 }
François Gaffie11d30102018-11-02 16:09:09 +01003906 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003907 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003908 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003909 return BAD_VALUE;
3910 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003911 audio_port_config sinkPortConfig = {};
3912 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3913 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003914
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003915 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
3916 // volume management purpose (tracking activity)
3917 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
3918 // in config XML to reach the sink so that is can be declared as available.
3919 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3920 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
3921 if (sourceDesc != nullptr) {
3922 // take care of dynamic routing for SwOutput selection,
3923 audio_attributes_t attributes = sourceDesc->attributes();
3924 audio_stream_type_t stream = sourceDesc->stream();
3925 audio_attributes_t resultAttr;
3926 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3927 config.sample_rate = sourceDesc->config().sample_rate;
3928 config.channel_mask = sourceDesc->config().channel_mask;
3929 config.format = sourceDesc->config().format;
3930 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3931 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3932 bool isRequestedDeviceForExclusiveUse = false;
3933 output_type_t outputType;
3934 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3935 &stream, sourceDesc->uid(), &config, &flags,
3936 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3937 nullptr, &outputType);
3938 if (output == AUDIO_IO_HANDLE_NONE) {
3939 ALOGV("%s no output for device %s",
3940 __FUNCTION__, sinkDevice->toString().c_str());
3941 return INVALID_OPERATION;
3942 }
3943 outputDesc = mOutputs.valueFor(output);
3944 if (outputDesc->isDuplicated()) {
3945 ALOGE("%s output is duplicated", __func__);
3946 return INVALID_OPERATION;
3947 }
3948 sourceDesc->setSwOutput(outputDesc);
3949 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07003950 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003951 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003952 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003953 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003954 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3955 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003956 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3957 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003958 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3959 (sourceDesc != nullptr &&
3960 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003961 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003962 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003963 return INVALID_OPERATION;
3964 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003965 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003966 SortedVector<audio_io_handle_t> outputs =
3967 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3968 // if the sink device is reachable via an opened output stream, request to
3969 // go via this output stream by adding a second source to the patch
3970 // description
3971 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003972 if (output != AUDIO_IO_HANDLE_NONE) {
3973 outputDesc = mOutputs.valueFor(output);
3974 if (outputDesc->isDuplicated()) {
3975 ALOGV("%s output for device %s is duplicated",
3976 __FUNCTION__, sinkDevice->toString().c_str());
3977 return INVALID_OPERATION;
3978 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003979 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02003980 }
3981 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003982 audio_port_config srcMixPortConfig = {};
3983 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01003984 // for volume control, we may need a valid stream
3985 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3986 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3987 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003988 }
Eric Laurent83b88082014-06-20 18:31:16 -07003989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 }
3991 // TODO: check from routing capabilities in config file and other conflicting patches
3992
François Gaffieafd4cea2019-11-18 15:50:22 +01003993 status_t status = installPatch(
3994 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003995 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003996 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 return INVALID_OPERATION;
3998 }
3999 } else {
4000 return BAD_VALUE;
4001 }
4002 } else {
4003 return BAD_VALUE;
4004 }
4005 return NO_ERROR;
4006}
4007
4008status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4009 uid_t uid)
4010{
4011 ALOGV("releaseAudioPatch() patch %d", handle);
4012
4013 ssize_t index = mAudioPatches.indexOfKey(handle);
4014
4015 if (index < 0) {
4016 return BAD_VALUE;
4017 }
4018 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004019 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4020 __func__, mUidCached, patchDesc->getUid(), uid);
4021 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004022 return INVALID_OPERATION;
4023 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004024 return releaseAudioPatchInternal(handle);
4025}
Eric Laurent6a94d692014-05-20 11:18:06 -07004026
François Gaffieafd4cea2019-11-18 15:50:22 +01004027status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4028 uint32_t delayMs)
4029{
4030 ALOGV("%s patch %d", __func__, handle);
4031 if (mAudioPatches.indexOfKey(handle) < 0) {
4032 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4033 return BAD_VALUE;
4034 }
4035 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004037 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004039 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004041 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 return BAD_VALUE;
4043 }
4044
François Gaffie11d30102018-11-02 16:09:09 +01004045 setOutputDevices(outputDesc,
4046 getNewOutputDevices(outputDesc, true /*fromCache*/),
4047 true,
4048 0,
4049 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004050 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4051 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004052 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004053 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004054 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004055 return BAD_VALUE;
4056 }
4057 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004058 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004059 true,
4060 NULL);
4061 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004062 status_t status =
4063 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4064 ALOGV("%s patch panel returned %d patchHandle %d",
4065 __func__, status, patchDesc->getAfHandle());
4066 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004067 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004068 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004069 // SW Bridge
4070 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4071 sp<SwAudioOutputDescriptor> outputDesc =
4072 mOutputs.getOutputFromId(patch->sources[1].id);
4073 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004074 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4075 // releaseOutput has already called closeOuput in case of direct output
4076 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004077 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004078 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4079 // force SwOutput patch removal as AF counter part patch has already gone.
4080 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4081 removeAudioPatch(outputDesc->getPatchHandle());
4082 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004083 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4084 setOutputDevices(outputDesc,
4085 getNewOutputDevices(outputDesc, true /*fromCache*/),
4086 true, /*force*/
4087 0,
4088 NULL);
4089 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004090 } else {
4091 return BAD_VALUE;
4092 }
4093 } else {
4094 return BAD_VALUE;
4095 }
4096 return NO_ERROR;
4097}
4098
4099status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4100 struct audio_patch *patches,
4101 unsigned int *generation)
4102{
François Gaffie53615e22015-03-19 09:24:12 +01004103 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004104 return BAD_VALUE;
4105 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004106 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004107 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004108}
4109
Eric Laurente1715a42014-05-20 11:30:42 -07004110status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004111{
Eric Laurente1715a42014-05-20 11:30:42 -07004112 ALOGV("setAudioPortConfig()");
4113
4114 if (config == NULL) {
4115 return BAD_VALUE;
4116 }
4117 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4118 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004119 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4120 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004121 }
4122
Eric Laurenta121f902014-06-03 13:32:54 -07004123 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004124 if (config->type == AUDIO_PORT_TYPE_MIX) {
4125 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004126 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004127 if (outputDesc == NULL) {
4128 return BAD_VALUE;
4129 }
Eric Laurent84c70242014-06-23 08:46:27 -07004130 ALOG_ASSERT(!outputDesc->isDuplicated(),
4131 "setAudioPortConfig() called on duplicated output %d",
4132 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004133 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004134 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004135 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004136 if (inputDesc == NULL) {
4137 return BAD_VALUE;
4138 }
Eric Laurenta121f902014-06-03 13:32:54 -07004139 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004140 } else {
4141 return BAD_VALUE;
4142 }
4143 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4144 sp<DeviceDescriptor> deviceDesc;
4145 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4146 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4147 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4148 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4149 } else {
4150 return BAD_VALUE;
4151 }
4152 if (deviceDesc == NULL) {
4153 return BAD_VALUE;
4154 }
Eric Laurenta121f902014-06-03 13:32:54 -07004155 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004156 } else {
4157 return BAD_VALUE;
4158 }
4159
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004160 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004161 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4162 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004163 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004164 audioPortConfig->toAudioPortConfig(&newConfig, config);
4165 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004166 }
Eric Laurenta121f902014-06-03 13:32:54 -07004167 if (status != NO_ERROR) {
4168 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004169 }
Eric Laurente1715a42014-05-20 11:30:42 -07004170
4171 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004172}
4173
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004174void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4175{
Eric Laurentd60560a2015-04-10 11:31:20 -07004176 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004177 clearAudioPatches(uid);
4178 clearSessionRoutes(uid);
4179}
4180
Eric Laurent6a94d692014-05-20 11:18:06 -07004181void AudioPolicyManager::clearAudioPatches(uid_t uid)
4182{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004183 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004185 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004186 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 }
4188 }
4189}
4190
François Gaffiec005e562018-11-06 15:04:49 +01004191void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004192{
François Gaffiec005e562018-11-06 15:04:49 +01004193 // Take the first attributes following the product strategy as it is used to retrieve the routed
4194 // device. All attributes wihin a strategy follows the same "routing strategy"
4195 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4196 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004197 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004198 for (size_t j = 0; j < mOutputs.size(); j++) {
4199 if (mOutputs.keyAt(j) == ouptutToSkip) {
4200 continue;
4201 }
4202 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004203 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004204 continue;
4205 }
4206 // If the default device for this strategy is on another output mix,
4207 // invalidate all tracks in this strategy to force re connection.
4208 // Otherwise select new device on the output mix.
4209 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004210 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4211 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004212 }
4213 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004214 setOutputDevices(
4215 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004216 }
4217 }
4218}
4219
4220void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4221{
4222 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004223 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004224 for (size_t i = 0; i < mOutputs.size(); i++) {
4225 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004226 for (const auto& client : outputDesc->getClientIterable()) {
4227 if (client->hasPreferredDevice() && client->uid() == uid) {
4228 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004229 auto clientStrategy = client->strategy();
4230 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4231 end(affectedStrategies)) {
4232 continue;
4233 }
4234 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004235 }
4236 }
4237 }
4238 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004239 for (const auto& strategy : affectedStrategies) {
4240 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004241 }
4242
4243 // remove input routes associated with this uid
4244 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004245 for (size_t i = 0; i < mInputs.size(); i++) {
4246 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004247 for (const auto& client : inputDesc->getClientIterable()) {
4248 if (client->hasPreferredDevice() && client->uid() == uid) {
4249 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4250 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004251 }
4252 }
4253 }
4254 // reroute inputs if necessary
4255 SortedVector<audio_io_handle_t> inputsToClose;
4256 for (size_t i = 0; i < mInputs.size(); i++) {
4257 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004258 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004259 inputsToClose.add(inputDesc->mIoHandle);
4260 }
4261 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004262 for (const auto& input : inputsToClose) {
4263 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004264 }
4265}
4266
Eric Laurentd60560a2015-04-10 11:31:20 -07004267void AudioPolicyManager::clearAudioSources(uid_t uid)
4268{
4269 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004270 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4271 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004272 stopAudioSource(mAudioSources.keyAt(i));
4273 }
4274 }
4275}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004276
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004277status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4278 audio_io_handle_t *ioHandle,
4279 audio_devices_t *device)
4280{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004281 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4282 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004283 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004284 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004285
François Gaffiedf372692015-03-19 10:43:27 +01004286 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004287}
4288
Eric Laurentd60560a2015-04-10 11:31:20 -07004289status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004290 const audio_attributes_t *attributes,
4291 audio_port_handle_t *portId,
4292 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004293{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004294 ALOGV("%s", __FUNCTION__);
4295 *portId = AUDIO_PORT_HANDLE_NONE;
4296
4297 if (source == NULL || attributes == NULL || portId == NULL) {
4298 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4299 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004300 return BAD_VALUE;
4301 }
4302
Eric Laurentd60560a2015-04-10 11:31:20 -07004303 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4304 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004305 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4306 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004307 return INVALID_OPERATION;
4308 }
4309
François Gaffie11d30102018-11-02 16:09:09 +01004310 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004311 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004312 String8(source->ext.device.address),
4313 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004314 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004315 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004316 return BAD_VALUE;
4317 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004318
jiabin4ef93452019-09-10 14:29:54 -07004319 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004320
François Gaffieaaac0fd2018-11-22 17:56:39 +01004321 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004322 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004323 mEngine->getStreamTypeForAttributes(*attributes),
4324 mEngine->getProductStrategyForAttributes(*attributes),
4325 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004326
4327 status_t status = connectAudioSource(sourceDesc);
4328 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004329 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004330 }
4331 return status;
4332}
4333
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004334status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004335{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004336 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004337
4338 // make sure we only have one patch per source.
4339 disconnectAudioSource(sourceDesc);
4340
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004341 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004342 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4343 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4344 sourceDesc->srcDevice()->type(),
4345 String8(sourceDesc->srcDevice()->address().c_str()),
4346 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004347 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004348 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004349 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004350 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004351 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4352 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4353 return INVALID_OPERATION;
4354 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004355 PatchBuilder patchBuilder;
4356 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4357 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4358 status_t status =
4359 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4360 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4361 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4362 return INVALID_OPERATION;
4363 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004364 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004365 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4366 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4367 if (swOutput != 0) {
4368 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004369 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004370 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004371 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004372 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004373 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004374 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004375 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004376 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004377 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004378 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004379 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004380 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4381 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004382 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004383 if (delayMs != 0) {
4384 usleep(delayMs * 1000);
4385 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004386 } else {
4387 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4388 if (hwOutputDesc != 0) {
4389 // create Hwoutput and add to mHwOutputs
4390 } else {
4391 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4392 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004393 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004394 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004395
4396FailureSourceActive:
4397 swOutput->stop();
4398 releaseOutput(sourceDesc->portId());
4399FailureSourceAdded:
4400 sourceDesc->setSwOutput(nullptr);
4401FailureReleasePatch:
4402 releaseAudioPatchInternal(handle);
4403 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004404}
4405
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004406status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004407{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004408 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4409 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004410 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004411 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004412 return BAD_VALUE;
4413 }
4414 status_t status = disconnectAudioSource(sourceDesc);
4415
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004416 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004417 return status;
4418}
4419
Andy Hung2ddee192015-12-18 17:34:44 -08004420status_t AudioPolicyManager::setMasterMono(bool mono)
4421{
4422 if (mMasterMono == mono) {
4423 return NO_ERROR;
4424 }
4425 mMasterMono = mono;
4426 // if enabling mono we close all offloaded devices, which will invalidate the
4427 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4428 // for recreating the new AudioTrack as non-offloaded PCM.
4429 //
4430 // If disabling mono, we leave all tracks as is: we don't know which clients
4431 // and tracks are able to be recreated as offloaded. The next "song" should
4432 // play back offloaded.
4433 if (mMasterMono) {
4434 Vector<audio_io_handle_t> offloaded;
4435 for (size_t i = 0; i < mOutputs.size(); ++i) {
4436 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4437 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4438 offloaded.push(desc->mIoHandle);
4439 }
4440 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004441 for (const auto& handle : offloaded) {
4442 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004443 }
4444 }
4445 // update master mono for all remaining outputs
4446 for (size_t i = 0; i < mOutputs.size(); ++i) {
4447 updateMono(mOutputs.keyAt(i));
4448 }
4449 return NO_ERROR;
4450}
4451
4452status_t AudioPolicyManager::getMasterMono(bool *mono)
4453{
4454 *mono = mMasterMono;
4455 return NO_ERROR;
4456}
4457
Eric Laurentac9cef52017-06-09 15:46:26 -07004458float AudioPolicyManager::getStreamVolumeDB(
4459 audio_stream_type_t stream, int index, audio_devices_t device)
4460{
jiabin9a3361e2019-10-01 09:38:30 -07004461 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004462}
4463
jiabin81772902018-04-02 17:52:27 -07004464status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4465 audio_format_t *surroundFormats,
4466 bool *surroundFormatsEnabled,
4467 bool reported)
4468{
4469 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4470 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4471 return BAD_VALUE;
4472 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004473 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4474 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004475
4476 size_t formatsWritten = 0;
4477 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004478 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004479 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004480 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004481 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004482 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4483 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004484 audio_devices_t deviceType = device->type();
4485 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4486 // returns formats reported by HDMI devices.
4487 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4488 continue;
4489 }
4490 // Formats reported by sink devices
4491 std::unordered_set<audio_format_t> formatset;
4492 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4493 formatset.insert(it->second.begin(), it->second.end());
4494 }
4495
4496 // Formats hard-coded in the in policy configuration file (if any).
4497 FormatVector encodedFormats = device->encodedFormats();
4498 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4499 // Filter the formats which are supported by the vendor hardware.
4500 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4501 if (mConfig.getSurroundFormats().count(*it) != 0) {
4502 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004503 } else {
4504 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004505 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004506 formats.insert(pair.first);
4507 break;
4508 }
4509 }
4510 }
4511 }
jiabin81772902018-04-02 17:52:27 -07004512 }
4513 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004514 for (const auto& pair : mConfig.getSurroundFormats()) {
4515 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004516 }
4517 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004518 *numSurroundFormats = formats.size();
4519 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4520 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004521 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004522 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004523 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004524 bool formatEnabled = true;
4525 switch (forceUse) {
4526 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4527 formatEnabled = mManualSurroundFormats.count(format) != 0;
4528 break;
4529 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4530 formatEnabled = false;
4531 break;
4532 default: // AUTO or ALWAYS => true
4533 break;
jiabin81772902018-04-02 17:52:27 -07004534 }
4535 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4536 }
jiabin81772902018-04-02 17:52:27 -07004537 }
4538 return NO_ERROR;
4539}
4540
4541status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4542{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004543 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004544 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4545 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004546 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004547 return BAD_VALUE;
4548 }
4549
Mikhail Naganov100f0122018-11-29 11:22:16 -08004550 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4551 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004552 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004553 return INVALID_OPERATION;
4554 }
4555
Mikhail Naganov100f0122018-11-29 11:22:16 -08004556 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004557 return NO_ERROR;
4558 }
4559
Mikhail Naganov100f0122018-11-29 11:22:16 -08004560 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004561 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004562 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004563 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004564 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004565 }
4566 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004567 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004568 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004569 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004570 }
4571 }
4572
4573 sp<SwAudioOutputDescriptor> outputDesc;
4574 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004575 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4576 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004577 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4578 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004579 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004580 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004581 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4582 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4583 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004584 name.c_str(),
4585 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004586 if (status != NO_ERROR) {
4587 continue;
4588 }
4589 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4590 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4591 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004592 name.c_str(),
4593 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004594 profileUpdated |= (status == NO_ERROR);
4595 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004596 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004597 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004598 AUDIO_DEVICE_IN_HDMI);
4599 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4600 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004601 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004602 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004603 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4604 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4605 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004606 name.c_str(),
4607 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004608 if (status != NO_ERROR) {
4609 continue;
4610 }
4611 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4612 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4613 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004614 name.c_str(),
4615 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004616 profileUpdated |= (status == NO_ERROR);
4617 }
4618
jiabin81772902018-04-02 17:52:27 -07004619 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004620 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004621 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004622 }
4623
4624 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4625}
4626
Eric Laurent5ada82e2019-08-29 17:53:54 -07004627void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004628{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004629 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004630 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004631 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004632 }
4633}
4634
jiabin6012f912018-11-02 17:06:30 -07004635bool AudioPolicyManager::isHapticPlaybackSupported()
4636{
4637 for (const auto& hwModule : mHwModules) {
4638 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4639 for (const auto &outProfile : outputProfiles) {
4640 struct audio_port audioPort;
4641 outProfile->toAudioPort(&audioPort);
4642 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4643 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4644 return true;
4645 }
4646 }
4647 }
4648 }
4649 return false;
4650}
4651
Eric Laurent8340e672019-11-06 11:01:08 -08004652bool AudioPolicyManager::isCallScreenModeSupported()
4653{
4654 return getConfig().isCallScreenModeSupported();
4655}
4656
4657
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004658status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004659{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004660 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004661 if (!sourceDesc->isConnected()) {
4662 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4663 return NO_ERROR;
4664 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004665 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4666 if (swOutput != 0) {
4667 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004668 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004669 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004670 }
jiabinbce0c1d2020-10-05 11:20:18 -07004671 if (releaseOutput(sourceDesc->portId())) {
4672 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4673 // no need to release audio patch here but just return NO_ERROR.
4674 return NO_ERROR;
4675 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004676 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004677 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004678 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004679 // close Hwoutput and remove from mHwOutputs
4680 } else {
4681 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4682 }
4683 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004684 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4685 sourceDesc->disconnect();
4686 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004687}
4688
François Gaffiec005e562018-11-06 15:04:49 +01004689sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4690 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004691{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004692 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004693 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004694 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004695 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004696 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4697 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004698 source = sourceDesc;
4699 break;
4700 }
4701 }
4702 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004703}
4704
Eric Laurente552edb2014-03-10 17:42:56 -07004705// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004706// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004707// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004708uint32_t AudioPolicyManager::nextAudioPortGeneration()
4709{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004710 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004711}
4712
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004713static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004714 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4715 !audioPolicyXmlConfigFile.empty()) {
4716 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4717 if (ret == NO_ERROR) {
4718 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004719 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004720 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004721 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004722 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004723}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004724
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004725AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4726 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004727 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004728 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004729 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004730 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004731 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004732 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004733 mAudioPortGeneration(1),
4734 mBeaconMuteRefCount(0),
4735 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004736 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004737 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004738 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004739 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004740{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004741}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004742
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004743AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4744 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4745{
4746 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004747}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004748
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004749void AudioPolicyManager::loadConfig() {
4750 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004751 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004752 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004753 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004754}
4755
4756status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004757 {
4758 auto engLib = EngineLibrary::load(
4759 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4760 if (!engLib) {
4761 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4762 return NO_INIT;
4763 }
4764 mEngine = engLib->createEngine();
4765 if (mEngine == nullptr) {
4766 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4767 return NO_INIT;
4768 }
François Gaffie2110e042015-03-24 08:41:51 +01004769 }
4770 mEngine->setObserver(this);
4771 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004772 if (status != NO_ERROR) {
4773 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4774 return status;
4775 }
François Gaffie2110e042015-03-24 08:41:51 +01004776
Eric Laurent1d69c872021-01-11 18:53:01 +01004777 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4778 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4779
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004780 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004781 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004782 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004783
Eric Laurent3a4311c2014-03-17 12:00:47 -07004784 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004785 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4786 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4787 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004788 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004789 }
jiabin9ff780e2018-03-19 18:19:52 -07004790 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004791 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004792 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004793 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004794 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004795 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004796 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004797 }
4798 }
4799 }
Eric Laurente552edb2014-03-10 17:42:56 -07004800
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004801 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004802
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004803 // Silence ALOGV statements
4804 property_set("log.tag." LOG_TAG, "D");
4805
Eric Laurente552edb2014-03-10 17:42:56 -07004806 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004807 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004808}
4809
Eric Laurente0720872014-03-11 09:30:41 -07004810AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004811{
Eric Laurente552edb2014-03-10 17:42:56 -07004812 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004813 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004814 }
4815 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004816 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004817 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004818 mAvailableOutputDevices.clear();
4819 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004820 mOutputs.clear();
4821 mInputs.clear();
4822 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004823 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004824 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004825}
4826
Eric Laurente0720872014-03-11 09:30:41 -07004827status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004828{
Eric Laurent87ffa392015-05-22 10:32:38 -07004829 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004830}
4831
Eric Laurente552edb2014-03-10 17:42:56 -07004832// ---
4833
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004834void AudioPolicyManager::onNewAudioModulesAvailable()
4835{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004836 DeviceVector newDevices;
4837 onNewAudioModulesAvailableInt(&newDevices);
4838 if (!newDevices.empty()) {
4839 nextAudioPortGeneration();
4840 mpClientInterface->onAudioPortListUpdate();
4841 }
4842}
4843
4844void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4845{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004846 for (const auto& hwModule : mHwModulesAll) {
4847 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4848 continue;
4849 }
4850 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4851 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4852 ALOGW("could not open HW module %s", hwModule->getName());
4853 continue;
4854 }
4855 mHwModules.push_back(hwModule);
4856 // open all output streams needed to access attached devices
4857 // except for direct output streams that are only opened when they are actually
4858 // required by an app.
4859 // This also validates mAvailableOutputDevices list
4860 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4861 if (!outProfile->canOpenNewIo()) {
4862 ALOGE("Invalid Output profile max open count %u for profile %s",
4863 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4864 continue;
4865 }
4866 if (!outProfile->hasSupportedDevices()) {
4867 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4868 continue;
4869 }
4870 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4871 mTtsOutputAvailable = true;
4872 }
4873
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004874 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4875 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4876 sp<DeviceDescriptor> supportedDevice = 0;
4877 if (supportedDevices.contains(mDefaultOutputDevice)) {
4878 supportedDevice = mDefaultOutputDevice;
4879 } else {
4880 // choose first device present in profile's SupportedDevices also part of
4881 // mAvailableOutputDevices.
4882 if (availProfileDevices.isEmpty()) {
4883 continue;
4884 }
4885 supportedDevice = availProfileDevices.itemAt(0);
4886 }
4887 if (!mOutputDevicesAll.contains(supportedDevice)) {
4888 continue;
4889 }
4890 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4891 mpClientInterface);
4892 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4893 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4894 AUDIO_STREAM_DEFAULT,
4895 AUDIO_OUTPUT_FLAG_NONE, &output);
4896 if (status != NO_ERROR) {
4897 ALOGW("Cannot open output stream for devices %s on hw module %s",
4898 supportedDevice->toString().c_str(), hwModule->getName());
4899 continue;
4900 }
4901 for (const auto &device : availProfileDevices) {
4902 // give a valid ID to an attached device once confirmed it is reachable
4903 if (!device->isAttached()) {
4904 device->attach(hwModule);
4905 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004906 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004907 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004908 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4909 }
4910 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004911 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004912 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4913 mPrimaryOutput = outputDesc;
4914 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004915 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4916 outputDesc->close();
4917 } else {
4918 addOutput(output, outputDesc);
4919 setOutputDevices(outputDesc,
4920 DeviceVector(supportedDevice),
4921 true,
4922 0,
4923 NULL);
4924 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004925 }
4926 // open input streams needed to access attached devices to validate
4927 // mAvailableInputDevices list
4928 for (const auto& inProfile : hwModule->getInputProfiles()) {
4929 if (!inProfile->canOpenNewIo()) {
4930 ALOGE("Invalid Input profile max open count %u for profile %s",
4931 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4932 continue;
4933 }
4934 if (!inProfile->hasSupportedDevices()) {
4935 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4936 continue;
4937 }
4938 // chose first device present in profile's SupportedDevices also part of
4939 // available input devices
4940 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4941 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4942 if (availProfileDevices.isEmpty()) {
4943 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4944 continue;
4945 }
4946 sp<AudioInputDescriptor> inputDesc =
4947 new AudioInputDescriptor(inProfile, mpClientInterface);
4948
4949 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4950 status_t status = inputDesc->open(nullptr,
4951 availProfileDevices.itemAt(0),
4952 AUDIO_SOURCE_MIC,
4953 AUDIO_INPUT_FLAG_NONE,
4954 &input);
4955 if (status != NO_ERROR) {
4956 ALOGW("Cannot open input stream for device %s on hw module %s",
4957 availProfileDevices.toString().c_str(),
4958 hwModule->getName());
4959 continue;
4960 }
4961 for (const auto &device : availProfileDevices) {
4962 // give a valid ID to an attached device once confirmed it is reachable
4963 if (!device->isAttached()) {
4964 device->attach(hwModule);
4965 device->importAudioPortAndPickAudioProfile(inProfile, true);
4966 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004967 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004968 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4969 }
4970 }
4971 inputDesc->close();
4972 }
4973 }
4974}
4975
Eric Laurent98e38192018-02-15 18:31:53 -08004976void AudioPolicyManager::addOutput(audio_io_handle_t output,
4977 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004978{
Eric Laurent1c333e22014-05-20 10:48:17 -07004979 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004980 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004981 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004982 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004984}
4985
François Gaffie53615e22015-03-19 09:24:12 +01004986void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4987{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004988 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
4989 ALOGV("%s: removing primary output", __func__);
4990 mPrimaryOutput = nullptr;
4991 }
François Gaffie53615e22015-03-19 09:24:12 +01004992 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004993 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004994}
4995
Eric Laurent98e38192018-02-15 18:31:53 -08004996void AudioPolicyManager::addInput(audio_io_handle_t input,
4997 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004998{
Eric Laurent1c333e22014-05-20 10:48:17 -07004999 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005000 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005001}
Eric Laurente552edb2014-03-10 17:42:56 -07005002
François Gaffie11d30102018-11-02 16:09:09 +01005003status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005004 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005005 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005006{
François Gaffie11d30102018-11-02 16:09:09 +01005007 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005008 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005009 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005010
François Gaffie11d30102018-11-02 16:09:09 +01005011 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005012 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005013 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005014 }
Eric Laurente552edb2014-03-10 17:42:56 -07005015
Eric Laurent3b73df72014-03-11 09:06:29 -07005016 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005017 // first call getAudioPort to get the supported attributes from the HAL
5018 struct audio_port_v7 port = {};
5019 device->toAudioPort(&port);
5020 status_t status = mpClientInterface->getAudioPort(&port);
5021 if (status == NO_ERROR) {
5022 device->importAudioPort(port);
5023 }
5024
5025 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005026 for (size_t i = 0; i < mOutputs.size(); i++) {
5027 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005028 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005029 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005030 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5031 mOutputs.keyAt(i), device->toString().c_str());
5032 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005033 }
5034 }
5035 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005037 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005038 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5039 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005040 if (profile->supportsDevice(device)) {
5041 profiles.add(profile);
5042 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5043 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005044 }
5045 }
5046 }
5047
Eric Laurent7b279bb2015-12-14 10:18:23 -08005048 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005049
Eric Laurente552edb2014-03-10 17:42:56 -07005050 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005051 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005052 return BAD_VALUE;
5053 }
5054
5055 // open outputs for matching profiles if needed. Direct outputs are also opened to
5056 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5057 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005058 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005059
5060 // nothing to do if one output is already opened for this profile
5061 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005062 for (j = 0; j < outputs.size(); j++) {
5063 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005064 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005065 // matching profile: save the sample rates, format and channel masks supported
5066 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005067 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005068 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005069 }
Eric Laurente552edb2014-03-10 17:42:56 -07005070 break;
5071 }
5072 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005073 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005074 continue;
5075 }
5076
Eric Laurent3974e3b2017-12-07 17:58:43 -08005077 if (!profile->canOpenNewIo()) {
5078 ALOGW("Max Output number %u already opened for this profile %s",
5079 profile->maxOpenCount, profile->getTagName().c_str());
5080 continue;
5081 }
5082
Eric Laurent83efe1c2017-07-09 16:51:08 -07005083 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005084 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005085 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5086 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005087 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005088 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005089 profiles.removeAt(profile_index);
5090 profile_index--;
5091 } else {
5092 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005093 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005094 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005095 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5096 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005097 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005098 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005099
François Gaffie11d30102018-11-02 16:09:09 +01005100 if (device_distinguishes_on_address(deviceType)) {
5101 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5102 device->toString().c_str());
5103 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5104 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005105 }
Eric Laurente552edb2014-03-10 17:42:56 -07005106 ALOGV("checkOutputsForDevice(): adding output %d", output);
5107 }
5108 }
5109
5110 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005111 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005112 return BAD_VALUE;
5113 }
Eric Laurentd4692962014-05-05 18:13:44 -07005114 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005115 // check if one opened output is not needed any more after disconnecting one device
5116 for (size_t i = 0; i < mOutputs.size(); i++) {
5117 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005118 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005119 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005120 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005121 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005122 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005123 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005124 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5125 mOutputs.keyAt(i));
5126 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005127 }
Eric Laurente552edb2014-03-10 17:42:56 -07005128 }
5129 }
Eric Laurentd4692962014-05-05 18:13:44 -07005130 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005131 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005132 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5133 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005134 if (!profile->supportsDevice(device)) {
5135 continue;
5136 }
5137 ALOGV("checkOutputsForDevice(): "
5138 "clearing direct output profile %zu on module %s",
5139 j, hwModule->getName());
5140 profile->clearAudioProfiles();
5141 if (!profile->hasDynamicAudioProfile()) {
5142 continue;
5143 }
5144 // When a device is disconnected, if there is an IOProfile that contains dynamic
5145 // profiles and supports the disconnected device, call getAudioPort to repopulate
5146 // the capabilities of the devices that is supported by the IOProfile.
5147 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5148 if (supportedDevice == device ||
5149 !mAvailableOutputDevices.contains(supportedDevice)) {
5150 continue;
5151 }
5152 struct audio_port_v7 port;
5153 supportedDevice->toAudioPort(&port);
5154 status_t status = mpClientInterface->getAudioPort(&port);
5155 if (status == NO_ERROR) {
5156 supportedDevice->importAudioPort(port);
5157 }
Eric Laurente552edb2014-03-10 17:42:56 -07005158 }
5159 }
5160 }
5161 }
5162 return NO_ERROR;
5163}
5164
François Gaffie11d30102018-11-02 16:09:09 +01005165status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005166 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005167{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005168 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005169
François Gaffie11d30102018-11-02 16:09:09 +01005170 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005171 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005172 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005173 }
5174
Eric Laurentd4692962014-05-05 18:13:44 -07005175 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005176 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005177 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005178 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005179 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005180 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005181 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005182 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005183
François Gaffie11d30102018-11-02 16:09:09 +01005184 if (profile->supportsDevice(device)) {
5185 profiles.add(profile);
5186 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5187 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005188 }
5189 }
5190 }
5191
Eric Laurent0dd51852019-04-19 18:18:58 -07005192 if (profiles.isEmpty()) {
5193 ALOGW("%s: No input profile available for device %s",
5194 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005195 return BAD_VALUE;
5196 }
5197
5198 // open inputs for matching profiles if needed. Direct inputs are also opened to
5199 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5200 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5201
Eric Laurent1c333e22014-05-20 10:48:17 -07005202 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005203
Eric Laurentd4692962014-05-05 18:13:44 -07005204 // nothing to do if one input is already opened for this profile
5205 size_t input_index;
5206 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5207 desc = mInputs.valueAt(input_index);
5208 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005209 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005210 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005211 }
Eric Laurentd4692962014-05-05 18:13:44 -07005212 break;
5213 }
5214 }
5215 if (input_index != mInputs.size()) {
5216 continue;
5217 }
5218
Eric Laurent3974e3b2017-12-07 17:58:43 -08005219 if (!profile->canOpenNewIo()) {
5220 ALOGW("Max Input number %u already opened for this profile %s",
5221 profile->maxOpenCount, profile->getTagName().c_str());
5222 continue;
5223 }
5224
Eric Laurentfe231122017-11-17 17:48:06 -08005225 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005226 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005227 status_t status = desc->open(nullptr,
5228 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005229 AUDIO_SOURCE_MIC,
5230 AUDIO_INPUT_FLAG_NONE,
5231 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005232
Eric Laurentcf2c0212014-07-25 16:20:43 -07005233 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005234 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005235 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005236 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005237 mpClientInterface->setParameters(input, String8(param));
5238 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005239 }
François Gaffie11d30102018-11-02 16:09:09 +01005240 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005241 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005242 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005243 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005244 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005245 }
5246
Eric Laurent0dd51852019-04-19 18:18:58 -07005247 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005248 addInput(input, desc);
5249 }
5250 } // endif input != 0
5251
Eric Laurentcf2c0212014-07-25 16:20:43 -07005252 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005253 ALOGW("%s could not open input for device %s", __func__,
5254 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005255 profiles.removeAt(profile_index);
5256 profile_index--;
5257 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005258 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005259 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005260 }
Eric Laurentd4692962014-05-05 18:13:44 -07005261 ALOGV("checkInputsForDevice(): adding input %d", input);
5262 }
5263 } // end scan profiles
5264
5265 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005266 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005267 return BAD_VALUE;
5268 }
5269 } else {
5270 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005271 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005272 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005273 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005274 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005275 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005276 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005277 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005278 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5279 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005280 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005281 }
5282 }
5283 }
5284 } // end disconnect
5285
5286 return NO_ERROR;
5287}
5288
5289
Eric Laurente0720872014-03-11 09:30:41 -07005290void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005291{
5292 ALOGV("closeOutput(%d)", output);
5293
François Gaffie1c878552018-11-22 16:53:21 +01005294 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5295 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005296 ALOGW("closeOutput() unknown output %d", output);
5297 return;
5298 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005299 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005300 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005301
Eric Laurente552edb2014-03-10 17:42:56 -07005302 // look for duplicated outputs connected to the output being removed.
5303 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005304 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5305 if (dupOutput->isDuplicated() &&
5306 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5307 sp<SwAudioOutputDescriptor> remainingOutput =
5308 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005309 // As all active tracks on duplicated output will be deleted,
5310 // and as they were also referenced on the other output, the reference
5311 // count for their stream type must be adjusted accordingly on
5312 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005313 const bool wasActive = remainingOutput->isActive();
5314 // Note: no-op on the closing output where all clients has already been set inactive
5315 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005316 // stop() will be a no op if the output is still active but is needed in case all
5317 // active streams refcounts where cleared above
5318 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005319 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005320 }
Eric Laurente552edb2014-03-10 17:42:56 -07005321 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5322 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5323
5324 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005325 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005326 }
5327 }
5328
Eric Laurent05b90f82014-08-27 15:32:29 -07005329 nextAudioPortGeneration();
5330
François Gaffie1c878552018-11-22 16:53:21 +01005331 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005332 if (index >= 0) {
5333 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005334 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5335 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005336 mAudioPatches.removeItemsAt(index);
5337 mpClientInterface->onAudioPatchListUpdate();
5338 }
5339
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005340 if (closingOutputWasActive) {
5341 closingOutput->stop();
5342 }
François Gaffie1c878552018-11-22 16:53:21 +01005343 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005344
François Gaffie53615e22015-03-19 09:24:12 +01005345 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005346 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005347
5348 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5349 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005350 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005351 bool directOutputOpen = false;
5352 for (size_t i = 0; i < mOutputs.size(); i++) {
5353 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5354 directOutputOpen = true;
5355 break;
5356 }
5357 }
5358 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005359 ALOGV("no direct outputs open, reset MSD patches");
5360 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5361 // how output devices for patching are resolved. Avoid by caching and reusing the
5362 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5363 // devices to patch to. This may be complicated by the fact that devices may become
5364 // unavailable.
5365 setMsdPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005366 }
5367 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005368}
5369
5370void AudioPolicyManager::closeInput(audio_io_handle_t input)
5371{
5372 ALOGV("closeInput(%d)", input);
5373
5374 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5375 if (inputDesc == NULL) {
5376 ALOGW("closeInput() unknown input %d", input);
5377 return;
5378 }
5379
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005381
François Gaffie11d30102018-11-02 16:09:09 +01005382 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005383 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005384 if (index >= 0) {
5385 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005386 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5387 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005388 mAudioPatches.removeItemsAt(index);
5389 mpClientInterface->onAudioPatchListUpdate();
5390 }
5391
Eric Laurentfe231122017-11-17 17:48:06 -08005392 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005393 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005394
François Gaffie11d30102018-11-02 16:09:09 +01005395 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5396 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005397 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005398 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005399 }
Eric Laurente552edb2014-03-10 17:42:56 -07005400}
5401
François Gaffie11d30102018-11-02 16:09:09 +01005402SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5403 const DeviceVector &devices,
5404 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005405{
5406 SortedVector<audio_io_handle_t> outputs;
5407
François Gaffie11d30102018-11-02 16:09:09 +01005408 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005409 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005410 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005411 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005412 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005413 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005414 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005415 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005416 outputs.add(openOutputs.keyAt(i));
5417 }
5418 }
5419 return outputs;
5420}
5421
Mikhail Naganov37977152018-07-11 15:54:44 -07005422void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5423{
5424 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5425 // output is suspended before any tracks are moved to it
5426 checkA2dpSuspend();
5427 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005428 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005429 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005430 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005431 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005432 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5433 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5434 // configuration changes will ultimately be rerouted correctly. We can still avoid
5435 // unnecessary rerouting by caching and reusing the arguments to
5436 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5437 // This may be complicated by the fact that devices may become unavailable.
5438 setMsdPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005439 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005440 // an event that changed routing likely occurred, inform upper layers
5441 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005442}
5443
François Gaffiec005e562018-11-06 15:04:49 +01005444bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5445 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005446{
François Gaffiec005e562018-11-06 15:04:49 +01005447 return mEngine->getProductStrategyForAttributes(lAttr) ==
5448 mEngine->getProductStrategyForAttributes(rAttr);
5449}
5450
Francois Gaffieff1eb522020-05-06 18:37:04 +02005451void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5452{
5453 for (size_t i = 0; i < mAudioSources.size(); i++) {
5454 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5455 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005456 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5457 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005458 connectAudioSource(sourceDesc);
5459 }
5460 }
5461}
5462
5463void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5464{
5465 for (size_t i = 0; i < mAudioSources.size(); i++) {
5466 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5467 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5468 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5469 disconnectAudioSource(sourceDesc);
5470 }
5471 }
5472}
5473
François Gaffiec005e562018-11-06 15:04:49 +01005474void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5475{
5476 auto psId = mEngine->getProductStrategyForAttributes(attr);
5477
5478 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5479 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005480
François Gaffie11d30102018-11-02 16:09:09 +01005481 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5482 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005483
Eric Laurentc209fe42020-06-05 18:11:23 -07005484 uint32_t maxLatency = 0;
5485 bool invalidate = false;
5486 // take into account dynamic audio policies related changes: if a client is now associated
5487 // to a different policy mix than at creation time, invalidate corresponding stream
5488 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5489 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5490 if (desc->isDuplicated()) {
5491 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005492 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005493 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5494 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5495 continue;
5496 }
5497 sp<AudioPolicyMix> primaryMix;
5498 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5499 client->flags(), primaryMix, nullptr);
5500 if (status != OK) {
5501 continue;
5502 }
yucliuf4de36d2020-09-14 14:57:56 -07005503 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005504 invalidate = true;
5505 if (desc->isStrategyActive(psId)) {
5506 maxLatency = desc->latency();
5507 }
5508 break;
5509 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005510 }
5511 }
5512
Eric Laurentc209fe42020-06-05 18:11:23 -07005513 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005514 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5515 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005516 for (audio_io_handle_t srcOut : srcOutputs) {
5517 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005518 if (desc == nullptr) continue;
5519
5520 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005521 maxLatency = desc->latency();
5522 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005523
5524 if (invalidate) continue;
5525
5526 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005527 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005528 // a client on a non direct outputs has necessarily a linear PCM format
5529 // so we can call selectOutput() safely
5530 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5531 client->flags(),
5532 client->config().format,
5533 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005534 client->config().sample_rate,
5535 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005536 if (newOutput != srcOut) {
5537 invalidate = true;
5538 break;
5539 }
5540 } else {
5541 sp<IOProfile> profile = getProfileForOutput(newDevices,
5542 client->config().sample_rate,
5543 client->config().format,
5544 client->config().channel_mask,
5545 client->flags(),
5546 true /* directOnly */);
5547 if (profile != desc->mProfile) {
5548 invalidate = true;
5549 break;
5550 }
5551 }
5552 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005553 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005554
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005555 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005556 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005557 std::to_string(srcOutputs[0]).c_str(),
5558 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005559 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005560 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005561 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005562 if (desc == nullptr) continue;
5563
5564 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005565 setStrategyMute(psId, true, desc);
5566 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005567 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005568 }
François Gaffiec005e562018-11-06 15:04:49 +01005569 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005570 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005571 connectAudioSource(source);
5572 }
Eric Laurente552edb2014-03-10 17:42:56 -07005573 }
5574
François Gaffiec005e562018-11-06 15:04:49 +01005575 // Move effects associated to this stream from previous output to new output
5576 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005577 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005578 }
François Gaffiec005e562018-11-06 15:04:49 +01005579 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005580 if (invalidate) {
5581 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5582 mpClientInterface->invalidateStream(stream);
5583 }
Eric Laurente552edb2014-03-10 17:42:56 -07005584 }
5585 }
5586}
5587
Eric Laurente0720872014-03-11 09:30:41 -07005588void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005589{
François Gaffiec005e562018-11-06 15:04:49 +01005590 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5591 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5592 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005593 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005594 }
Eric Laurente552edb2014-03-10 17:42:56 -07005595}
5596
Kevin Rocard153f92d2018-12-18 18:33:28 -08005597void AudioPolicyManager::checkSecondaryOutputs() {
5598 std::set<audio_stream_type_t> streamsToInvalidate;
5599 for (size_t i = 0; i < mOutputs.size(); i++) {
5600 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5601 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005602 sp<AudioPolicyMix> primaryMix;
5603 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005604 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005605 client->flags(), primaryMix, &secondaryMixes);
5606 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5607 for (auto &secondaryMix : secondaryMixes) {
5608 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5609 if (outputDesc != nullptr &&
5610 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5611 secondaryDescs.push_back(outputDesc);
5612 }
5613 }
5614
Kevin Rocard94114a22019-04-01 19:38:23 -07005615 if (status != OK ||
5616 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005617 client->getSecondaryOutputs().end(),
5618 secondaryDescs.begin(), secondaryDescs.end())) {
5619 streamsToInvalidate.insert(client->stream());
5620 }
5621 }
5622 }
5623 for (audio_stream_type_t stream : streamsToInvalidate) {
5624 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5625 mpClientInterface->invalidateStream(stream);
5626 }
5627}
5628
Eric Laurent2517af32020-11-25 15:31:27 +01005629bool AudioPolicyManager::isScoRequestedForComm() const {
5630 AudioDeviceTypeAddrVector devices;
5631 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5632 for (const auto &device : devices) {
5633 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5634 return true;
5635 }
5636 }
5637 return false;
5638}
5639
Eric Laurente0720872014-03-11 09:30:41 -07005640void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005641{
François Gaffie53615e22015-03-19 09:24:12 +01005642 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005643 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005644 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005645 return;
5646 }
5647
Eric Laurent3a4311c2014-03-17 12:00:47 -07005648 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005649 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5650 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005651 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005652
5653 // if suspended, restore A2DP output if:
5654 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005655 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005656 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005657 //
Eric Laurentf732e072016-08-03 19:30:28 -07005658 // if not suspended, suspend A2DP output if:
5659 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005660 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005661 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005662 //
5663 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005664 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005665 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005666 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005667 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005668
5669 mpClientInterface->restoreOutput(a2dpOutput);
5670 mA2dpSuspended = false;
5671 }
5672 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005673 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005674 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005675 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005676 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005677
5678 mpClientInterface->suspendOutput(a2dpOutput);
5679 mA2dpSuspended = true;
5680 }
5681 }
5682}
5683
François Gaffie11d30102018-11-02 16:09:09 +01005684DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5685 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005686{
François Gaffie11d30102018-11-02 16:09:09 +01005687 DeviceVector devices;
5688
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005689 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005690 if (index >= 0) {
5691 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005692 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005693 ALOGV("%s device %s forced by patch %d", __func__,
5694 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5695 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005696 }
5697 }
5698
Dean Wheatley514b4312020-06-17 21:45:00 +10005699 // Do not retrieve engine device for outputs through MSD
5700 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5701 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5702 return outputDesc->devices();
5703 }
5704
Eric Laurent97ac8712018-07-27 18:59:02 -07005705 // Honor explicit routing requests only if no client using default routing is active on this
5706 // input: a specific app can not force routing for other apps by setting a preferred device.
5707 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005708 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005709 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005710 if (device != nullptr) {
5711 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005712 }
5713
François Gaffiea807ef92018-11-05 10:44:33 +01005714 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5715 // of setForceUse / Default Bus device here
5716 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5717 if (device != nullptr) {
5718 return DeviceVector(device);
5719 }
5720
François Gaffiec005e562018-11-06 15:04:49 +01005721 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5722 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5723 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305724 auto hasStreamActive = [&](auto stream) {
5725 return hasStream(streams, stream) && isStreamActive(stream, 0);
5726 };
Eric Laurent484e9272018-06-07 17:29:23 -07005727
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305728 auto doGetOutputDevicesForVoice = [&]() {
5729 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5730 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5731 (isInCall() ||
5732 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
5733 };
5734
5735 // With low-latency playing on speaker, music on WFD, when the first low-latency
5736 // output is stopped, getNewOutputDevices checks for a product strategy
5737 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
5738 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
5739 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5740 // stream is associated to the output descriptor.
5741 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5742 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5743 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5744 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005745 // Retrieval of devices for voice DL is done on primary output profile, cannot
5746 // check the route (would force modifying configuration file for this profile)
5747 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5748 break;
5749 }
Eric Laurente552edb2014-03-10 17:42:56 -07005750 }
François Gaffiec005e562018-11-06 15:04:49 +01005751 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005752 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005753}
5754
François Gaffie11d30102018-11-02 16:09:09 +01005755sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5756 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005757{
François Gaffie11d30102018-11-02 16:09:09 +01005758 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005759
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005760 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005761 if (index >= 0) {
5762 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005763 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005764 ALOGV("getNewInputDevice() device %s forced by patch %d",
5765 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5766 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005767 }
5768 }
5769
Eric Laurent97ac8712018-07-27 18:59:02 -07005770 // Honor explicit routing requests only if no client using default routing is active on this
5771 // input: a specific app can not force routing for other apps by setting a preferred device.
5772 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005773 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5774 if (device != nullptr) {
5775 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005776 }
5777
Eric Laurentdc95a252018-04-12 12:46:56 -07005778 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005779 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005780 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5781 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5782 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005783 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005784 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005785 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005786 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005787
Eric Laurente552edb2014-03-10 17:42:56 -07005788 return device;
5789}
5790
Eric Laurent794fde22016-03-11 09:50:45 -08005791bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5792 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005793 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005794}
5795
Eric Laurente0720872014-03-11 09:30:41 -07005796audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005797 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005798 // getOutputDevicesForStream's behavior for invalid streams.
5799 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5800 // device for music stream), but we want to return the empty set.
5801 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005802 return AUDIO_DEVICE_NONE;
5803 }
François Gaffie11d30102018-11-02 16:09:09 +01005804 DeviceVector activeDevices;
5805 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005806 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5807 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005808 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005809 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005810 }
François Gaffiec005e562018-11-06 15:04:49 +01005811 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005812 devices.merge(curDevices);
5813 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005814 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005815 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005816 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005817 }
5818 }
Eric Laurente552edb2014-03-10 17:42:56 -07005819 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005820
Eric Laurentb0688d62018-08-14 15:49:18 -07005821 // Favor devices selected on active streams if any to report correct device in case of
5822 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005823 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005824 devices = activeDevices;
5825 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005826 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5827 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005828 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005829 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005830 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005831 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005832 }
jiabin9a3361e2019-10-01 09:38:30 -07005833 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5834 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005835}
5836
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005837status_t AudioPolicyManager::getDevicesForAttributes(
5838 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5839 if (devices == nullptr) {
5840 return BAD_VALUE;
5841 }
5842 // check dynamic policies but only for primary descriptors (secondary not used for audible
5843 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005844 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005845 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005846 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005847 if (status != OK) {
5848 return status;
5849 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005850 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5851 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5852 devices->push_back(device);
5853 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005854 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005855 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5856 for (const auto& device : curDevices) {
5857 devices->push_back(device->getDeviceTypeAddr());
5858 }
5859 return NO_ERROR;
5860}
5861
Eric Laurente0720872014-03-11 09:30:41 -07005862void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005863 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005864 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005865 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005866 updateDevicesAndOutputs();
5867 break;
5868 default:
5869 break;
5870 }
5871}
5872
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005873uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005874
5875 // skip beacon mute management if a dedicated TTS output is available
5876 if (mTtsOutputAvailable) {
5877 return 0;
5878 }
5879
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005880 switch(event) {
5881 case STARTING_OUTPUT:
5882 mBeaconMuteRefCount++;
5883 break;
5884 case STOPPING_OUTPUT:
5885 if (mBeaconMuteRefCount > 0) {
5886 mBeaconMuteRefCount--;
5887 }
5888 break;
5889 case STARTING_BEACON:
5890 mBeaconPlayingRefCount++;
5891 break;
5892 case STOPPING_BEACON:
5893 if (mBeaconPlayingRefCount > 0) {
5894 mBeaconPlayingRefCount--;
5895 }
5896 break;
5897 }
5898
5899 if (mBeaconMuteRefCount > 0) {
5900 // any playback causes beacon to be muted
5901 return setBeaconMute(true);
5902 } else {
5903 // no other playback: unmute when beacon starts playing, mute when it stops
5904 return setBeaconMute(mBeaconPlayingRefCount == 0);
5905 }
5906}
5907
5908uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5909 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5910 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5911 // keep track of muted state to avoid repeating mute/unmute operations
5912 if (mBeaconMuted != mute) {
5913 // mute/unmute AUDIO_STREAM_TTS on all outputs
5914 ALOGV("\t muting %d", mute);
5915 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005916 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005917 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005919 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005920 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005921 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005922 maxLatency = latency;
5923 }
5924 }
5925 mBeaconMuted = mute;
5926 return maxLatency;
5927 }
5928 return 0;
5929}
5930
Eric Laurente0720872014-03-11 09:30:41 -07005931void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005932{
François Gaffiec005e562018-11-06 15:04:49 +01005933 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005934 mPreviousOutputs = mOutputs;
5935}
5936
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005937uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005938 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005939 uint32_t delayMs)
5940{
5941 // mute/unmute strategies using an incompatible device combination
5942 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5943 // if unmuting, unmute only after the specified delay
5944 if (outputDesc->isDuplicated()) {
5945 return 0;
5946 }
5947
5948 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005949 DeviceVector devices = outputDesc->devices();
5950 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005951
François Gaffiec005e562018-11-06 15:04:49 +01005952 auto productStrategies = mEngine->getOrderedProductStrategies();
5953 for (const auto &productStrategy : productStrategies) {
5954 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5955 DeviceVector curDevices =
5956 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5957 curDevices = curDevices.filter(outputDesc->supportedDevices());
5958 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005959 bool doMute = false;
5960
François Gaffiec005e562018-11-06 15:04:49 +01005961 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005962 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005963 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5964 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005965 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005966 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005967 }
Eric Laurent99401132014-05-07 19:48:15 -07005968 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005969 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005970 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005971 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005972 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005973 continue;
5974 }
François Gaffiec005e562018-11-06 15:04:49 +01005975 ALOGVV("%s() %s (curDevice %s)", __func__,
5976 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5977 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5978 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005979 if (mute) {
5980 // FIXME: should not need to double latency if volume could be applied
5981 // immediately by the audioflinger mixer. We must account for the delay
5982 // between now and the next time the audioflinger thread for this output
5983 // will process a buffer (which corresponds to one buffer size,
5984 // usually 1/2 or 1/4 of the latency).
5985 if (muteWaitMs < desc->latency() * 2) {
5986 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005987 }
5988 }
5989 }
5990 }
5991 }
5992 }
5993
Eric Laurent99401132014-05-07 19:48:15 -07005994 // temporary mute output if device selection changes to avoid volume bursts due to
5995 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005996 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005997 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5998 // temporary mute duration is conservatively set to 4 times the reported latency
5999 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6000 if (muteWaitMs < tempMuteWaitMs) {
6001 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006002 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006003 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6004 // make sure that we do not start the temporary mute period too early in case of
6005 // delayed device change
6006 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6007 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006008 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006009 }
6010 }
6011
Eric Laurente552edb2014-03-10 17:42:56 -07006012 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6013 if (muteWaitMs > delayMs) {
6014 muteWaitMs -= delayMs;
6015 usleep(muteWaitMs * 1000);
6016 return muteWaitMs;
6017 }
6018 return 0;
6019}
6020
François Gaffie11d30102018-11-02 16:09:09 +01006021uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6022 const DeviceVector &devices,
6023 bool force,
6024 int delayMs,
6025 audio_patch_handle_t *patchHandle,
6026 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006027{
François Gaffie11d30102018-11-02 16:09:09 +01006028 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006029 uint32_t muteWaitMs;
6030
6031 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006032 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6033 nullptr /* patchHandle */, requiresMuteCheck);
6034 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6035 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006036 return muteWaitMs;
6037 }
Eric Laurente552edb2014-03-10 17:42:56 -07006038
6039 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006040 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006041 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006042
François Gaffie11d30102018-11-02 16:09:09 +01006043 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6044
6045 if (!filteredDevices.isEmpty()) {
6046 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006047 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006048
6049 // if the outputs are not materially active, there is no need to mute.
6050 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006051 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006052 } else {
6053 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6054 muteWaitMs = 0;
6055 }
Eric Laurente552edb2014-03-10 17:42:56 -07006056
Eric Laurent79ea9582020-06-11 18:49:24 -07006057 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6058 // output profile or if new device is not supported AND previous device(s) is(are) still
6059 // available (otherwise reset device must be done on the output)
6060 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6061 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6062 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6063 // restore previous device after evaluating strategy mute state
6064 outputDesc->setDevices(prevDevices);
6065 return muteWaitMs;
6066 }
6067
Eric Laurente552edb2014-03-10 17:42:56 -07006068 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006069 // the requested device is AUDIO_DEVICE_NONE
6070 // OR the requested device is the same as current device
6071 // AND force is not specified
6072 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006073 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006074 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006075 !force && outputDesc->getPatchHandle() != 0) {
6076 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6077 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006078 return muteWaitMs;
6079 }
6080
François Gaffie11d30102018-11-02 16:09:09 +01006081 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006082
Eric Laurente552edb2014-03-10 17:42:56 -07006083 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006084 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006085 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006086 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006087 PatchBuilder patchBuilder;
6088 patchBuilder.addSource(outputDesc);
6089 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6090 for (const auto &filteredDevice : filteredDevices) {
6091 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006092 }
6093
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006094 // Add half reported latency to delayMs when muteWaitMs is null in order
6095 // to avoid disordered sequence of muting volume and changing devices.
6096 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6097 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006098 }
Eric Laurente552edb2014-03-10 17:42:56 -07006099
6100 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006101 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006102
6103 return muteWaitMs;
6104}
6105
Eric Laurentc75307b2015-03-17 15:29:32 -07006106status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006107 int delayMs,
6108 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006109{
Eric Laurent6a94d692014-05-20 11:18:06 -07006110 ssize_t index;
6111 if (patchHandle) {
6112 index = mAudioPatches.indexOfKey(*patchHandle);
6113 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006114 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006115 }
6116 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006117 return INVALID_OPERATION;
6118 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006119 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006120 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006121 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006122 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006123 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006124 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006125 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006126 return status;
6127}
6128
6129status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006130 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006131 bool force,
6132 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006133{
6134 status_t status = NO_ERROR;
6135
Eric Laurent1f2f2232014-06-02 12:01:23 -07006136 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006137 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6138 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006139
François Gaffie11d30102018-11-02 16:09:09 +01006140 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006141 PatchBuilder patchBuilder;
6142 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006143 // AUDIO_SOURCE_HOTWORD is for internal use only:
6144 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006145 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6146 auto result = usecase;
6147 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6148 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6149 }
6150 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006151 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006152 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006153 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006154 }
6155 }
6156 return status;
6157}
6158
Eric Laurent6a94d692014-05-20 11:18:06 -07006159status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6160 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006161{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006162 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006163 ssize_t index;
6164 if (patchHandle) {
6165 index = mAudioPatches.indexOfKey(*patchHandle);
6166 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006167 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006168 }
6169 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006170 return INVALID_OPERATION;
6171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006172 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006173 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006174 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006175 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006176 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006177 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006178 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006179 return status;
6180}
6181
François Gaffie11d30102018-11-02 16:09:09 +01006182sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006183 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006184 audio_format_t& format,
6185 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006186 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006187{
6188 // Choose an input profile based on the requested capture parameters: select the first available
6189 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006190 //
6191 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6192 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006193
Glenn Kasten730b9262018-03-29 15:01:26 -07006194 sp<IOProfile> firstInexact;
6195 uint32_t updatedSamplingRate = 0;
6196 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6197 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006198 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006199 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006200 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006201 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006202 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006203 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006204 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006205 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006206 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006207 &channelMask /*updatedChannelMask*/,
6208 // FIXME ugly cast
6209 (audio_output_flags_t) flags,
6210 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006211 return profile;
6212 }
François Gaffie11d30102018-11-02 16:09:09 +01006213 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006214 samplingRate,
6215 &updatedSamplingRate,
6216 format,
6217 &updatedFormat,
6218 channelMask,
6219 &updatedChannelMask,
6220 // FIXME ugly cast
6221 (audio_output_flags_t) flags,
6222 false /*exactMatchRequiredForInputFlags*/)) {
6223 firstInexact = profile;
6224 }
6225
Eric Laurente552edb2014-03-10 17:42:56 -07006226 }
6227 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006228 if (firstInexact != nullptr) {
6229 samplingRate = updatedSamplingRate;
6230 format = updatedFormat;
6231 channelMask = updatedChannelMask;
6232 return firstInexact;
6233 }
Eric Laurente552edb2014-03-10 17:42:56 -07006234 return NULL;
6235}
6236
François Gaffieaaac0fd2018-11-22 17:56:39 +01006237float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6238 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006239 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006240 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006241{
jiabin9a3361e2019-10-01 09:38:30 -07006242 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006243
6244 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6245 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6246 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6247 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006248 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6249 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6250 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6251 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006252 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006253
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006254 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006255 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6256 mOutputs.isActive(ringVolumeSrc, 0)) {
6257 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006258 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006259 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006260 }
6261
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006262 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006263 if ((volumeSource != callVolumeSrc && (isInCall() ||
6264 mOutputs.isActiveLocally(callVolumeSrc))) &&
6265 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6266 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6267 volumeSource == alarmVolumeSrc ||
6268 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6269 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6270 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006271 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006272 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006273 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006274 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006275 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006276 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006277 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6278 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6279 // programmatically muted.
6280 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6281 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6282 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006283 bool exemptFromCapping =
6284 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6285 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006286 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6287 volumeSource, volumeDb);
6288 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006289 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6290 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6291 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006292 }
6293 }
Eric Laurente552edb2014-03-10 17:42:56 -07006294 // if a headset is connected, apply the following rules to ring tones and notifications
6295 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006296 // - always attenuate notifications volume by 6dB
6297 // - attenuate ring tones volume by 6dB unless music is not playing and
6298 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006299 // - if music is playing, always limit the volume to current music volume,
6300 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006301 if (!Intersection(deviceTypes,
6302 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6303 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006304 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6305 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006306 ((volumeSource == alarmVolumeSrc ||
6307 volumeSource == ringVolumeSrc) ||
6308 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6309 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6310 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6311 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6312 curves.canBeMuted()) {
6313
Eric Laurente552edb2014-03-10 17:42:56 -07006314 // when the phone is ringing we must consider that music could have been paused just before
6315 // by the music application and behave as if music was active if the last music track was
6316 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006317 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006318 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006319 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006320 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006321 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6322 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006323 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006324 float musicVolDb = computeVolume(musicCurves,
6325 musicVolumeSrc,
6326 musicCurves.getVolumeIndex(musicDevice),
6327 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006328 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6329 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6330 if (volumeDb > minVolDb) {
6331 volumeDb = minVolDb;
6332 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006333 }
jiabin9a3361e2019-10-01 09:38:30 -07006334 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6335 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006336 // on A2DP, also ensure notification volume is not too low compared to media when
6337 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006338 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006339 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006340 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6341 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006342 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6343 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006344 }
6345 }
jiabin9a3361e2019-10-01 09:38:30 -07006346 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006347 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006348 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006349 }
6350 }
6351
François Gaffie43c73442018-11-08 08:21:55 +01006352 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006353}
6354
Eric Laurent3839bc02018-07-10 18:33:34 -07006355int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006356 VolumeSource fromVolumeSource,
6357 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006358{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006359 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006360 return srcIndex;
6361 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006362 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6363 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006364 float minSrc = (float)srcCurves.getVolumeIndexMin();
6365 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6366 float minDst = (float)dstCurves.getVolumeIndexMin();
6367 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006368
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006369 // preserve mute request or correct range
6370 if (srcIndex < minSrc) {
6371 if (srcIndex == 0) {
6372 return 0;
6373 }
6374 srcIndex = minSrc;
6375 } else if (srcIndex > maxSrc) {
6376 srcIndex = maxSrc;
6377 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006378 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6379}
6380
François Gaffieaaac0fd2018-11-22 17:56:39 +01006381status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6382 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006383 int index,
6384 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006385 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006386 int delayMs,
6387 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006388{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006389 // do not change actual attributes volume if the attributes is muted
6390 if (outputDesc->isMuted(volumeSource)) {
6391 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6392 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006393 return NO_ERROR;
6394 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006395 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6396 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6397 bool isVoiceVolSrc = callVolSrc == volumeSource;
6398 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6399
Eric Laurent2517af32020-11-25 15:31:27 +01006400 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006401 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006402 // if sco and call follow same curves, bypass forceUseForComm
6403 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006404 ((isVoiceVolSrc && isScoRequested) ||
6405 (isBtScoVolSrc && !isScoRequested))) {
6406 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6407 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006408 // Do not return an error here as AudioService will always set both voice call
6409 // and bluetooth SCO volumes due to stream aliasing.
6410 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006411 }
jiabin9a3361e2019-10-01 09:38:30 -07006412 if (deviceTypes.empty()) {
6413 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006414 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006415
jiabin9a3361e2019-10-01 09:38:30 -07006416 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6417 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006418 // Force VoIP volume to max for bluetooth SCO device except if muted
6419 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006420 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006421 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006422 }
jiabin9a3361e2019-10-01 09:38:30 -07006423 outputDesc->setVolume(
6424 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006425
François Gaffieaaac0fd2018-11-22 17:56:39 +01006426 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006427 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006428 // 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 +01006429 if (isVoiceVolSrc) {
6430 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006431 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006432 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006433 }
Eric Laurent18fba842016-03-31 14:41:26 -07006434 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006435 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6436 mLastVoiceVolume = voiceVolume;
6437 }
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439 return NO_ERROR;
6440}
6441
Eric Laurentc75307b2015-03-17 15:29:32 -07006442void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006443 const DeviceTypeSet& deviceTypes,
6444 int delayMs,
6445 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006446{
jiabincd510522020-01-22 09:40:55 -08006447 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006448 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6449 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6450 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006451 curves.getVolumeIndex(deviceTypes),
6452 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006453 }
6454}
6455
François Gaffiec005e562018-11-06 15:04:49 +01006456void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6457 bool on,
6458 const sp<AudioOutputDescriptor>& outputDesc,
6459 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006460 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006461{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006462 std::vector<VolumeSource> sourcesToMute;
6463 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6464 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6465 toString(attributes).c_str(), on, outputDesc->getId());
6466 VolumeSource source = toVolumeSource(attributes);
6467 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6468 sourcesToMute.push_back(source);
6469 }
Eric Laurente552edb2014-03-10 17:42:56 -07006470 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006471 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006472 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006473 }
6474
Eric Laurente552edb2014-03-10 17:42:56 -07006475}
6476
François Gaffieaaac0fd2018-11-22 17:56:39 +01006477void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6478 bool on,
6479 const sp<AudioOutputDescriptor>& outputDesc,
6480 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006481 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006482{
jiabin9a3361e2019-10-01 09:38:30 -07006483 if (deviceTypes.empty()) {
6484 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006485 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006486 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006487 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006488 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006489 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006490 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6491 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6492 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006493 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006494 }
6495 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006496 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6497 // ignored
6498 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006499 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006500 if (!outputDesc->isMuted(volumeSource)) {
6501 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006502 return;
6503 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006504 if (outputDesc->decMuteCount(volumeSource) == 0) {
6505 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006506 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006507 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006508 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006509 delayMs);
6510 }
6511 }
6512}
6513
François Gaffie53615e22015-03-19 09:24:12 +01006514bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6515{
François Gaffiec005e562018-11-06 15:04:49 +01006516 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006517 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6518 return true;
6519 }
6520
6521 // has known usage?
6522 switch (paa->usage) {
6523 case AUDIO_USAGE_UNKNOWN:
6524 case AUDIO_USAGE_MEDIA:
6525 case AUDIO_USAGE_VOICE_COMMUNICATION:
6526 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6527 case AUDIO_USAGE_ALARM:
6528 case AUDIO_USAGE_NOTIFICATION:
6529 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6530 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6531 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6532 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6533 case AUDIO_USAGE_NOTIFICATION_EVENT:
6534 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6535 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6536 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6537 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006538 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006539 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006540 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006541 case AUDIO_USAGE_EMERGENCY:
6542 case AUDIO_USAGE_SAFETY:
6543 case AUDIO_USAGE_VEHICLE_STATUS:
6544 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006545 break;
6546 default:
6547 return false;
6548 }
6549 return true;
6550}
6551
François Gaffie2110e042015-03-24 08:41:51 +01006552audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6553{
6554 return mEngine->getForceUse(usage);
6555}
6556
6557bool AudioPolicyManager::isInCall()
6558{
6559 return isStateInCall(mEngine->getPhoneState());
6560}
6561
6562bool AudioPolicyManager::isStateInCall(int state)
6563{
6564 return is_state_in_call(state);
6565}
6566
Eric Laurent74b71512019-11-06 17:21:57 -08006567bool AudioPolicyManager::isCallAudioAccessible()
6568{
6569 audio_mode_t mode = mEngine->getPhoneState();
6570 return (mode == AUDIO_MODE_IN_CALL)
6571 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6572 || (mode == AUDIO_MODE_CALL_SCREEN);
6573}
6574
Eric Laurentd60560a2015-04-10 11:31:20 -07006575void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6576{
6577 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006578 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006579 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006580 sourceDesc->sinkDevice()->equals(deviceDesc))
6581 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006582 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006583 }
6584 }
6585
6586 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6587 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6588 bool release = false;
6589 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6590 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6591 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6592 source->ext.device.type == deviceDesc->type()) {
6593 release = true;
6594 }
6595 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006596 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006597 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6598 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6599 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006600 sink->ext.device.type == deviceDesc->type() &&
6601 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6602 || strncmp(sink->ext.device.address, address,
6603 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006604 release = true;
6605 }
6606 }
6607 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006608 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6609 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006610 }
6611 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006612
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006613 mInputs.clearSessionRoutesForDevice(deviceDesc);
6614
Francois Gaffie716e1432019-01-14 16:58:59 +01006615 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006616}
6617
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006618void AudioPolicyManager::modifySurroundFormats(
6619 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006620 std::unordered_set<audio_format_t> enforcedSurround(
6621 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006622 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6623 for (const auto& pair : mConfig.getSurroundFormats()) {
6624 allSurround.insert(pair.first);
6625 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6626 }
Phil Burk09bc4612016-02-24 15:58:15 -08006627
6628 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6629 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006630 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006631 // This is the resulting set of formats depending on the surround mode:
6632 // 'all surround' = allSurround
6633 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6634 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6635 // 'manual surround' = mManualSurroundFormats
6636 // AUTO: formats v 'enforced surround'
6637 // ALWAYS: formats v 'all surround' v 'enforced surround'
6638 // NEVER: formats ^ 'non-surround'
6639 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006640
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006641 std::unordered_set<audio_format_t> formatSet;
6642 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6643 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006644 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006645 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006646 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006647 formatSet.insert(*formatIter);
6648 }
6649 }
6650 } else {
6651 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6652 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006653 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006654
jiabin81772902018-04-02 17:52:27 -07006655 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006656 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006657 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6658 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6659 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006660 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006661 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6662 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6663 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006664 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006665 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006666 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006667 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006668 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006669 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006670}
6671
jiabin06e4bab2019-07-29 10:13:34 -07006672void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6673 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006674 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6675 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6676
6677 // If NEVER, then remove support for channelMasks > stereo.
6678 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006679 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6680 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006681 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6682 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006683 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006684 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006685 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006686 }
6687 }
jiabin81772902018-04-02 17:52:27 -07006688 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6689 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6690 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006691 bool supports5dot1 = false;
6692 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006693 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006694 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6695 supports5dot1 = true;
6696 break;
6697 }
6698 }
6699 // If not then add 5.1 support.
6700 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006701 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006702 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006703 }
Phil Burk09bc4612016-02-24 15:58:15 -08006704 }
6705}
6706
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006707void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006708 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006709 AudioProfileVector &profiles)
6710{
6711 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006712 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006713
François Gaffie112b0af2015-11-19 16:13:25 +01006714 // Format MUST be checked first to update the list of AudioProfile
6715 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006716 reply = mpClientInterface->getParameters(
6717 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006718 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006719 AudioParameter repliedParameters(reply);
6720 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006721 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006722 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6723 return;
6724 }
Phil Burk09bc4612016-02-24 15:58:15 -08006725 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006726 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006727 if (device == AUDIO_DEVICE_OUT_HDMI
6728 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006729 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006730 }
jiabin3e277cc2019-09-10 14:27:34 -07006731 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006732 }
François Gaffie112b0af2015-11-19 16:13:25 +01006733
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006734 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006735 ChannelMaskSet channelMasks;
6736 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006737 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006738 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006739
6740 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006741 reply = mpClientInterface->getParameters(
6742 ioHandle,
6743 requestedParameters.toString() + ";" +
6744 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006745 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006746 AudioParameter repliedParameters(reply);
6747 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006748 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006749 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006750 }
6751 }
6752 if (profiles.hasDynamicChannelsFor(format)) {
6753 reply = mpClientInterface->getParameters(ioHandle,
6754 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006755 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006756 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006757 AudioParameter repliedParameters(reply);
6758 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006759 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006760 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006761 if (device == AUDIO_DEVICE_OUT_HDMI
6762 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006763 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006764 }
François Gaffie112b0af2015-11-19 16:13:25 +01006765 }
6766 }
jiabin3e277cc2019-09-10 14:27:34 -07006767 addDynamicAudioProfileAndSort(
6768 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006769 }
6770}
Eric Laurentd60560a2015-04-10 11:31:20 -07006771
Mikhail Naganovdc769682018-05-04 15:34:08 -07006772status_t AudioPolicyManager::installPatch(const char *caller,
6773 audio_patch_handle_t *patchHandle,
6774 AudioIODescriptorInterface *ioDescriptor,
6775 const struct audio_patch *patch,
6776 int delayMs)
6777{
6778 ssize_t index = mAudioPatches.indexOfKey(
6779 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6780 *patchHandle : ioDescriptor->getPatchHandle());
6781 sp<AudioPatch> patchDesc;
6782 status_t status = installPatch(
6783 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6784 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006785 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006786 }
6787 return status;
6788}
6789
6790status_t AudioPolicyManager::installPatch(const char *caller,
6791 ssize_t index,
6792 audio_patch_handle_t *patchHandle,
6793 const struct audio_patch *patch,
6794 int delayMs,
6795 uid_t uid,
6796 sp<AudioPatch> *patchDescPtr)
6797{
6798 sp<AudioPatch> patchDesc;
6799 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6800 if (index >= 0) {
6801 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006802 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006803 }
6804
6805 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6806 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6807 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6808 if (status == NO_ERROR) {
6809 if (index < 0) {
6810 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006811 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006812 } else {
6813 patchDesc->mPatch = *patch;
6814 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006815 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006816 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006817 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006818 }
6819 nextAudioPortGeneration();
6820 mpClientInterface->onAudioPatchListUpdate();
6821 }
6822 if (patchDescPtr) *patchDescPtr = patchDesc;
6823 return status;
6824}
6825
jiabinbce0c1d2020-10-05 11:20:18 -07006826bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6827{
6828 const TrackClientVector activeClients = output->getActiveClients();
6829 if (activeClients.empty()) {
6830 return true;
6831 }
6832 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6833 if (index < 0) {
6834 ALOGE("%s, no audio patch found while there are active clients on output %d",
6835 __func__, output->getId());
6836 return false;
6837 }
6838 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6839 DeviceVector routedDevices;
6840 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6841 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6842 patchDesc->mPatch.sinks[i].id);
6843 if (device == nullptr) {
6844 ALOGE("%s, no audio device found with id(%d)",
6845 __func__, patchDesc->mPatch.sinks[i].id);
6846 return false;
6847 }
6848 routedDevices.add(device);
6849 }
6850 for (const auto& client : activeClients) {
6851 // TODO: b/175343099 only travel the valid client
6852 sp<DeviceDescriptor> preferredDevice =
6853 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6854 if (mEngine->getOutputDevicesForAttributes(
6855 client->attributes(), preferredDevice, false) == routedDevices) {
6856 return false;
6857 }
6858 }
6859 return true;
6860}
6861
6862sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6863 const sp<IOProfile>& profile, const DeviceVector& devices)
6864{
6865 for (const auto& device : devices) {
6866 // TODO: This should be checking if the profile supports the device combo.
6867 if (!profile->supportsDevice(device)) {
6868 return nullptr;
6869 }
6870 }
6871 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6872 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6873 status_t status = desc->open(nullptr, devices,
6874 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6875 if (status != NO_ERROR) {
6876 return nullptr;
6877 }
6878
6879 // Here is where the out_set_parameters() for card & device gets called
6880 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6881 const audio_devices_t deviceType = device->type();
6882 const String8 &address = String8(device->address().c_str());
6883 if (!address.isEmpty()) {
6884 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6885 mpClientInterface->setParameters(output, String8(param));
6886 free(param);
6887 }
6888 updateAudioProfiles(device, output, profile->getAudioProfiles());
6889 if (!profile->hasValidAudioProfile()) {
6890 ALOGW("%s() missing param", __func__);
6891 desc->close();
6892 return nullptr;
6893 } else if (profile->hasDynamicAudioProfile()) {
6894 desc->close();
6895 output = AUDIO_IO_HANDLE_NONE;
6896 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6897 profile->pickAudioProfile(
6898 config.sample_rate, config.channel_mask, config.format);
6899 config.offload_info.sample_rate = config.sample_rate;
6900 config.offload_info.channel_mask = config.channel_mask;
6901 config.offload_info.format = config.format;
6902
6903 status = desc->open(&config, devices,
6904 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6905 if (status != NO_ERROR) {
6906 return nullptr;
6907 }
6908 }
6909
6910 addOutput(output, desc);
6911 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6912 sp<AudioPolicyMix> policyMix;
6913 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6914 policyMix->setOutput(desc);
6915 desc->mPolicyMix = policyMix;
6916 } else {
6917 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6918 address.string());
6919 }
6920
6921 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6922 // no duplicated output for direct outputs and
6923 // outputs used by dynamic policy mixes
6924 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6925
6926 //TODO: configure audio effect output stage here
6927
6928 // open a duplicating output thread for the new output and the primary output
6929 sp<SwAudioOutputDescriptor> dupOutputDesc =
6930 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6931 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6932 if (status == NO_ERROR) {
6933 // add duplicated output descriptor
6934 addOutput(duplicatedOutput, dupOutputDesc);
6935 } else {
6936 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6937 mPrimaryOutput->mIoHandle, output);
6938 desc->close();
6939 removeOutput(output);
6940 nextAudioPortGeneration();
6941 return nullptr;
6942 }
6943 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006944 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6945 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
6946 mPrimaryOutput = desc;
6947 }
jiabinbce0c1d2020-10-05 11:20:18 -07006948 return desc;
6949}
6950
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006951} // namespace android