blob: aac244c8e541dc23cc623a2d4ae36db2dae34363 [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))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700249 closeOutput(output);
250 }
Eric Laurente552edb2014-03-10 17:42:56 -0700251 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700252 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
253 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700254 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700255 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800256 };
257
258 if (doCheckForDeviceAndOutputChanges) {
259 checkForDeviceAndOutputChanges(checkCloseOutputs);
260 } else {
261 checkCloseOutputs();
262 }
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Eric Laurent87ffa392015-05-22 10:32:38 -0700264 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100265 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
266 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700267 }
jiabinbce0c1d2020-10-05 11:20:18 -0700268 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700270 const DeviceVector activeMediaDevices =
271 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
274 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100275 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700276 // do not force device change on duplicated output because if device is 0, it will
277 // also force a device 0 for the two outputs it is duplicated to which may override
278 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100279 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100280 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700281 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700282 // always force when disconnecting (a non-duplicated device)
283 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100284 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700285 }
jiabinbce0c1d2020-10-05 11:20:18 -0700286 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
287 desc->devices() != activeMediaDevices &&
288 desc->supportsDevicesForPlayback(activeMediaDevices)) {
289 // Reopen the output to query the dynamic profiles when there is not active
290 // clients or all active clients will be rerouted. Otherwise, set the flag
291 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
292 // can be reopened to query dynamic profiles when all clients are inactive.
293 if (areAllActiveTracksRerouted(desc)) {
294 outputsToReopen.push_back(mOutputs.keyAt(i));
295 } else {
296 desc->mPendingReopenToQueryProfiles = true;
297 }
298 }
299 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
300 // Clear the flag that previously set for re-querying profiles.
301 desc->mPendingReopenToQueryProfiles = false;
302 }
303 }
304 for (const auto& output : outputsToReopen) {
305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
306 closeOutput(output);
307 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
309
Eric Laurentd60560a2015-04-10 11:31:20 -0700310 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100311 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700312 }
313
Eric Laurent72aa32f2014-05-30 18:51:48 -0700314 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700315 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } // end if is output device
317
Eric Laurente552edb2014-03-10 17:42:56 -0700318 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700319 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700321 switch (state)
322 {
323 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700324 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700327 return INVALID_OPERATION;
328 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700329
330 if (mAvailableInputDevices.add(device) < 0) {
331 return NO_MEMORY;
332 }
333
François Gaffie44481e72016-04-20 07:49:57 +0200334 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
335 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100336 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200337
Eric Laurent0dd51852019-04-19 18:18:58 -0700338 if (checkInputsForDevice(device, state) != NO_ERROR) {
339 mAvailableInputDevices.remove(device);
340
François Gaffie11d30102018-11-02 16:09:09 +0100341 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100342
343 mHwModules.cleanUpForDevice(device);
344
Eric Laurentd4692962014-05-05 18:13:44 -0700345 return INVALID_OPERATION;
346 }
347
Eric Laurentd4692962014-05-05 18:13:44 -0700348 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700349
350 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700351 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700354 return INVALID_OPERATION;
355 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700356
François Gaffie11d30102018-11-02 16:09:09 +0100357 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700358
359 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100360 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700361
François Gaffie11d30102018-11-02 16:09:09 +0100362 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700363
364 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100365
366 // remove device from mReportedFormatsMap cache
367 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700368 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700369
370 default:
François Gaffie11d30102018-11-02 16:09:09 +0100371 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700372 return BAD_VALUE;
373 }
374
Eric Laurent736a1022019-03-27 18:28:46 -0700375 // Propagate device availability to Engine
376 setEngineDeviceConnectionState(device, state);
377
Eric Laurent0dd51852019-04-19 18:18:58 -0700378 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700379 // As the input device list can impact the output device selection, update
380 // getDeviceForStrategy() cache
381 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700382
Eric Laurent87ffa392015-05-22 10:32:38 -0700383 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
385 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700386 }
387
Eric Laurentd60560a2015-04-10 11:31:20 -0700388 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700390 }
391
Eric Laurentb52c1522014-05-20 11:27:36 -0700392 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700393 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700394 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700395
François Gaffie11d30102018-11-02 16:09:09 +0100396 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700397 return BAD_VALUE;
398}
399
Eric Laurent736a1022019-03-27 18:28:46 -0700400void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
401 audio_policy_dev_state_t state) {
402
403 // the Engine does not have to know about remote submix devices used by dynamic audio policies
404 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
405 return;
406 }
407 mEngine->setDeviceConnectionState(device, state);
408}
409
410
Eric Laurente0720872014-03-11 09:30:41 -0700411audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100412 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700413{
Eric Laurent634b7142016-04-20 13:48:02 -0700414 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800415 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
416 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700417 (strlen(device_address) != 0)/*matchAddress*/);
418
419 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100420 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700421 device, device_address);
422 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
423 }
François Gaffie53615e22015-03-19 09:24:12 +0100424
Eric Laurent3a4311c2014-03-17 12:00:47 -0700425 DeviceVector *deviceVector;
426
Eric Laurente552edb2014-03-10 17:42:56 -0700427 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700428 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700429 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 deviceVector = &mAvailableInputDevices;
431 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100432 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700433 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700434 }
Eric Laurent634b7142016-04-20 13:48:02 -0700435
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800436 return (deviceVector->getDevice(
437 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800439}
440
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800441status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
442 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800443 const char *device_name,
444 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800445{
446 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700447 String8 reply;
448 AudioParameter param;
449 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800450
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800451 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
452 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800453
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800454 // connect/disconnect only 1 device at a time
455 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
456
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800457 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700458 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800459 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800460 // Nothing to do: device is not connected
461 return NO_ERROR;
462 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800463 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800464
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700465 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 // configure codecs.
467 // Handle two specific cases by sending a set parameter to
468 // configure A2DP codecs. No need to toggle device state.
469 // Case 1: A2DP active device switches from primary to primary
470 // module
471 // Case 2: A2DP device config changes on primary module.
jiabin9a3361e2019-10-01 09:38:30 -0700472 if (audio_is_a2dp_out_device(device)) {
473 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
475 if (availablePrimaryOutputDevices().contains(devDesc) &&
476 (module != 0 && module->getHandle() == primaryHandle)) {
477 reply = mpClientInterface->getParameters(
478 AUDIO_IO_HANDLE_NONE,
479 String8(AudioParameter::keyReconfigA2dpSupported));
480 AudioParameter repliedParameters(reply);
481 repliedParameters.getInt(
482 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
483 if (isReconfigA2dpSupported) {
484 const String8 key(AudioParameter::keyReconfigA2dp);
485 param.add(key, String8("true"));
486 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
487 devDesc->setEncodedFormat(encodedFormat);
488 return NO_ERROR;
489 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700490 }
491 }
cnx421bd2dcc42020-07-11 14:58:44 +0800492 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
493 for (size_t i = 0; i < mOutputs.size(); i++) {
494 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
495 // mute media strategies and delay device switch by the largest
496 // This avoid sending the music tail into the earpiece or headset.
497 setStrategyMute(musicStrategy, true, desc);
498 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
499 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
500 nullptr, true /*fromCache*/).types());
501 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800502 // Toggle the device state: UNAVAILABLE -> AVAILABLE
503 // This will force reading again the device configuration
504 status = setDeviceConnectionState(device,
505 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 device_address, device_name,
507 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 if (status != NO_ERROR) {
509 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
510 status);
511 return status;
512 }
513
514 status = setDeviceConnectionState(device,
515 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517 if (status != NO_ERROR) {
518 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
519 status);
520 return status;
521 }
522
523 return NO_ERROR;
524}
525
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800526status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
527 std::vector<audio_format_t> *formats)
528{
529 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800530 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800531 std::unordered_set<audio_format_t> formatSet;
532 sp<HwModule> primaryModule =
533 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700534 if (primaryModule == nullptr) {
535 ALOGE("%s() unable to get primary module", __func__);
536 return NO_INIT;
537 }
jiabin9a3361e2019-10-01 09:38:30 -0700538 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
539 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800540 for (const auto& device : declaredDevices) {
541 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800542 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800543 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800544 return status;
545}
546
François Gaffie11d30102018-11-02 16:09:09 +0100547uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700548{
549 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100550 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700551 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700552
jiabin9a3361e2019-10-01 09:38:30 -0700553 if(!hasPrimaryOutput() ||
554 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700555 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700556 }
François Gaffie11d30102018-11-02 16:09:09 +0100557 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
558
Francois Gaffie716e1432019-01-14 16:58:59 +0100559 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100560 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100561 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100562
563 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100564 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565
566 // release existing RX patch if any
567 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100568 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700569 mCallRxPatch.clear();
570 }
571 // release TX patch if any
572 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100573 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700574 mCallTxPatch.clear();
575 }
576
François Gaffie9eb18552018-11-05 10:33:26 +0100577 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700578 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100579 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700580 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100581 // retrieve Rx Source and Tx Sink device descriptors
582 sp<DeviceDescriptor> rxSourceDevice =
583 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
584 String8(),
585 AUDIO_FORMAT_DEFAULT);
586 sp<DeviceDescriptor> txSinkDevice =
587 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
588 String8(),
589 AUDIO_FORMAT_DEFAULT);
590
591 // RX and TX Telephony device are declared by Primary Audio HAL
592 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
593 (telephonyRxModule->getHalVersionMajor() >= 3)) {
594 if (rxSourceDevice == 0 || txSinkDevice == 0) {
595 // RX / TX Telephony device(s) is(are) not currently available
596 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
597 return muteWaitMs;
598 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100599 // createAudioPatchInternal now supports both HW / SW bridging
600 createRxPatch = true;
601 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100602 } else {
603 // If the RX device is on the primary HW module, then use legacy routing method for
604 // voice calls via setOutputDevice() on primary output.
605 // Otherwise, create two audio patches for TX and RX path.
606 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
607 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700608 // If the TX device is also on the primary HW module, setOutputDevice() will take care
609 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100610 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
611 (txSinkDevice != 0);
612 }
613 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
614 // Otherwise, create two audio patches for TX and RX path.
615 if (!createRxPatch) {
616 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700617 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100618 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800619
620 // If the TX device is on the primary HW module but RX device is
621 // on other HW module, SinkMetaData of telephony input should handle it
622 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700623 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700624 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100625 // terminate active capture if on the same HW module as the call TX source device
626 // FIXME: would be better to refine to only inputs whose profile connects to the
627 // call TX device but this information is not in the audio patch and logic here must be
628 // symmetric to the one in startInput()
629 for (const auto& activeDesc : mInputs.getActiveInputs()) {
630 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
631 closeActiveClients(activeDesc);
632 }
633 }
François Gaffie9eb18552018-11-05 10:33:26 +0100634 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800635 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700636
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800637 return muteWaitMs;
638}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700639
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800640sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100641 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700642 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700643
François Gaffie11d30102018-11-02 16:09:09 +0100644 if (device == nullptr) {
645 return nullptr;
646 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100647
648 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800649 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100650 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800651 addSource(mAvailableInputDevices.getDevice(
652 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800653 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100654 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800655 addSink(mAvailableOutputDevices.getDevice(
656 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800657 }
658
François Gaffieafd4cea2019-11-18 15:50:22 +0100659 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
660 status_t status =
661 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
662 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
663 if (status != NO_ERROR || index < 0) {
664 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
665 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800666 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100667 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800668}
669
Mikhail Naganov100f0122018-11-29 11:22:16 -0800670bool AudioPolicyManager::isDeviceOfModule(
671 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
672 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
673 if (module != 0) {
674 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
675 .indexOf(devDesc) != NAME_NOT_FOUND
676 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
677 .indexOf(devDesc) != NAME_NOT_FOUND;
678 }
679 return false;
680}
681
Eric Laurente0720872014-03-11 09:30:41 -0700682void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700683{
684 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100685 // store previous phone state for management of sonification strategy below
686 int oldState = mEngine->getPhoneState();
687
688 if (mEngine->setPhoneState(state) != NO_ERROR) {
689 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700690 return;
691 }
François Gaffie2110e042015-03-24 08:41:51 +0100692 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700693 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700694 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700695 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800696 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700697 }
698
François Gaffie2110e042015-03-24 08:41:51 +0100699 /**
700 * Switching to or from incall state or switching between telephony and VoIP lead to force
701 * routing command.
702 */
Eric Laurent74b71512019-11-06 17:21:57 -0800703 bool force = ((isStateInCall(oldState) != isStateInCall(state))
704 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700705
706 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700707 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700708
Eric Laurente552edb2014-03-10 17:42:56 -0700709 int delayMs = 0;
710 if (isStateInCall(state)) {
711 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100712 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
713 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700714 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700715 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700716 // mute media and sonification strategies and delay device switch by the largest
717 // latency of any output where either strategy is active.
718 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100719 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
720 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
721 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700722 (delayMs < (int)desc->latency()*2)) {
723 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725 setStrategyMute(musicStrategy, true, desc);
726 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
727 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
728 nullptr, true /*fromCache*/).types());
729 setStrategyMute(sonificationStrategy, true, desc);
730 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
731 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
732 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700733 }
734 }
735
Eric Laurent87ffa392015-05-22 10:32:38 -0700736 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100737 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700738 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100739 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700740 // force routing command to audio hardware when ending call
741 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100742 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
743 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700744 }
Eric Laurente552edb2014-03-10 17:42:56 -0700745
Eric Laurent87ffa392015-05-22 10:32:38 -0700746 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100747 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700748 } else if (oldState == AUDIO_MODE_IN_CALL) {
749 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100750 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700751 mCallRxPatch.clear();
752 }
753 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100754 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700755 mCallTxPatch.clear();
756 }
François Gaffie11d30102018-11-02 16:09:09 +0100757 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700758 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100759 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700761 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700762
763 // reevaluate routing on all outputs in case tracks have been started during the call
764 for (size_t i = 0; i < mOutputs.size(); i++) {
765 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100766 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700767 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100768 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700769 }
770 }
771
Eric Laurente552edb2014-03-10 17:42:56 -0700772 if (isStateInCall(state)) {
773 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700774 // force reevaluating accessibility routing when call starts
775 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700776 }
777
778 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100779 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
780 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700781}
782
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700783audio_mode_t AudioPolicyManager::getPhoneState() {
784 return mEngine->getPhoneState();
785}
786
Eric Laurente0720872014-03-11 09:30:41 -0700787void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100788 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700789{
François Gaffie2110e042015-03-24 08:41:51 +0100790 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700791 if (config == mEngine->getForceUse(usage)) {
792 return;
793 }
Eric Laurente552edb2014-03-10 17:42:56 -0700794
François Gaffie2110e042015-03-24 08:41:51 +0100795 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
796 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
797 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700798 }
François Gaffie2110e042015-03-24 08:41:51 +0100799 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
800 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
801 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700802
803 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700804 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800805
Eric Laurent22fcda22019-05-17 16:28:47 -0700806 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
807 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
808 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
809 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
810 }
811
Eric Laurentdc462862016-07-19 12:29:53 -0700812 //FIXME: workaround for truncated touch sounds
813 // to be removed when the problem is handled by system UI
814 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700815 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
816 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
817 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700818
819 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100820 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700821}
822
Eric Laurente0720872014-03-11 09:30:41 -0700823void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 ALOGV("setSystemProperty() property %s, value %s", property, value);
826}
827
Michael Chana94fbb22018-04-24 14:31:19 +1000828// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
829// search to profiles for direct outputs.
830sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100831 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000832 uint32_t samplingRate,
833 audio_format_t format,
834 audio_channel_mask_t channelMask,
835 audio_output_flags_t flags,
836 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700837{
Michael Chana94fbb22018-04-24 14:31:19 +1000838 if (directOnly) {
839 // only retain flags that will drive the direct output profile selection
840 // if explicitly requested
841 static const uint32_t kRelevantFlags =
842 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700843 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000844 flags =
845 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
846 }
Eric Laurent861a6282015-05-18 15:40:16 -0700847
848 sp<IOProfile> profile;
849
Mikhail Naganovd4120142017-12-06 15:49:22 -0800850 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800851 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100852 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700853 samplingRate, NULL /*updatedSamplingRate*/,
854 format, NULL /*updatedFormat*/,
855 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700856 flags)) {
857 continue;
858 }
859 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100860 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700861 continue;
862 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800863 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700864 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800865 continue;
866 }
Michael Chana94fbb22018-04-24 14:31:19 +1000867 if (!directOnly) return curProfile;
868 // when searching for direct outputs, if several profiles are compatible, give priority
869 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100870 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700871 continue;
872 }
873 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100874 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700875 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700876 }
Eric Laurente552edb2014-03-10 17:42:56 -0700877 }
878 }
Eric Laurent861a6282015-05-18 15:40:16 -0700879 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700880}
881
Eric Laurentf4e63452017-11-06 19:31:46 +0000882audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700883{
François Gaffiec005e562018-11-06 15:04:49 +0100884 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800885
886 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
887 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
888 // format, flags, etc. This may result in some discrepancy for functions that utilize
889 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
890 // and AudioSystem::getOutputSamplingRate().
891
François Gaffie11d30102018-11-02 16:09:09 +0100892 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700893 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700894
François Gaffie11d30102018-11-02 16:09:09 +0100895 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
896 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000897 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700898}
899
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700900status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
901 const audio_attributes_t *srcAttr,
902 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700903{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700904 if (srcAttr != NULL) {
905 if (!isValidAttributes(srcAttr)) {
906 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
907 __func__,
908 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
909 srcAttr->tags);
910 return BAD_VALUE;
911 }
912 *dstAttr = *srcAttr;
913 } else {
914 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
915 ALOGE("%s: invalid stream type", __func__);
916 return BAD_VALUE;
917 }
François Gaffiec005e562018-11-06 15:04:49 +0100918 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700919 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700920
921 // Only honor audibility enforced when required. The client will be
922 // forced to reconnect if the forced usage changes.
923 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700924 dstAttr->flags = static_cast<audio_flags_mask_t>(
925 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700926 }
927
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 return NO_ERROR;
929}
930
Kevin Rocard153f92d2018-12-18 18:33:28 -0800931status_t AudioPolicyManager::getOutputForAttrInt(
932 audio_attributes_t *resultAttr,
933 audio_io_handle_t *output,
934 audio_session_t session,
935 const audio_attributes_t *attr,
936 audio_stream_type_t *stream,
937 uid_t uid,
938 const audio_config_t *config,
939 audio_output_flags_t *flags,
940 audio_port_handle_t *selectedDeviceId,
941 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700942 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800943 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700944{
François Gaffiec005e562018-11-06 15:04:49 +0100945 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100946 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100947 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100948 const sp<DeviceDescriptor> requestedDevice =
949 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
950
Eric Laurent8a1095a2019-11-08 14:44:16 -0800951 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700952 status_t status = getAudioAttributes(resultAttr, attr, *stream);
953 if (status != NO_ERROR) {
954 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700955 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700956 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700957 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700958 }
François Gaffiec005e562018-11-06 15:04:49 +0100959 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700960
François Gaffiec005e562018-11-06 15:04:49 +0100961 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
962 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700963
Kevin Rocard153f92d2018-12-18 18:33:28 -0800964 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
965 // otherwise, fallback to the dynamic policies, if none match, query the engine.
966 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700967 sp<AudioPolicyMix> primaryMix;
968 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700969 if (status != OK) {
970 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800971 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700972
Kevin Rocard153f92d2018-12-18 18:33:28 -0800973 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700974 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800975
976 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700977 if ((usePrimaryOutputFromPolicyMixes
978 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800979 && !audio_is_linear_pcm(config->format)) {
980 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800981 return BAD_VALUE;
982 }
983 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700984 sp<DeviceDescriptor> deviceDesc =
985 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
986 primaryMix->mDeviceAddress,
987 AUDIO_FORMAT_DEFAULT);
988 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700989 if (deviceDesc != nullptr
990 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700991 audio_io_handle_t newOutput;
992 status = openDirectOutput(
993 *stream, session, config,
994 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
995 DeviceVector(deviceDesc), &newOutput);
996 if (status != NO_ERROR) {
997 policyDesc = nullptr;
998 } else {
999 policyDesc = mOutputs.valueFor(newOutput);
1000 primaryMix->setOutput(policyDesc);
1001 }
1002 }
1003 if (policyDesc != nullptr) {
1004 policyDesc->mPolicyMix = primaryMix;
1005 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001006 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001007
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001008 ALOGV("getOutputForAttr() returns output %d", *output);
1009 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1010 *outputType = API_OUT_MIX_PLAYBACK;
1011 } else {
1012 *outputType = API_OUTPUT_LEGACY;
1013 }
1014 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001015 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001016 }
François Gaffiec005e562018-11-06 15:04:49 +01001017 // Virtual sources must always be dynamicaly or explicitly routed
1018 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1019 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1020 return BAD_VALUE;
1021 }
1022 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1023 // in order to let the choice of the order to future vendor engine
1024 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001025
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001026 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001027 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001028 }
1029
Nadav Barb2f18162018-07-18 13:01:53 +03001030 // Set incall music only if device was explicitly set, and fallback to the device which is
1031 // chosen by the engine if not.
1032 // FIXME: provide a more generic approach which is not device specific and move this back
1033 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001034 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001035 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001036 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001037 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001038 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001039 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001040 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001041 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001042 }
1043 }
1044
François Gaffiec005e562018-11-06 15:04:49 +01001045 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1046 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1047 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001048
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001049 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001050 if (!msdDevices.isEmpty()) {
1051 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001052 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1053 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1054 ALOGV("%s() Using MSD devices %s instead of devices %s",
1055 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1056 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001057 } else {
1058 *output = AUDIO_IO_HANDLE_NONE;
1059 }
1060 }
1061 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001062 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001063 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001064 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001065 if (*output == AUDIO_IO_HANDLE_NONE) {
1066 return INVALID_OPERATION;
1067 }
Paul McLeanaa981192015-03-21 09:55:15 -07001068
François Gaffiec005e562018-11-06 15:04:49 +01001069 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001070
Eric Laurent8a1095a2019-11-08 14:44:16 -08001071 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1072 *outputType = API_OUTPUT_TELEPHONY_TX;
1073 } else {
1074 *outputType = API_OUTPUT_LEGACY;
1075 }
1076
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001077 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1078
1079 return NO_ERROR;
1080}
1081
1082status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1083 audio_io_handle_t *output,
1084 audio_session_t session,
1085 audio_stream_type_t *stream,
1086 uid_t uid,
1087 const audio_config_t *config,
1088 audio_output_flags_t *flags,
1089 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001090 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001091 std::vector<audio_io_handle_t> *secondaryOutputs,
1092 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001093{
1094 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1095 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1096 return INVALID_OPERATION;
1097 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001098 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001099 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001100 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001101 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001102 const sp<DeviceDescriptor> requestedDevice =
1103 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1104
1105 // Prevent from storing invalid requested device id in clients
1106 const audio_port_handle_t sanitizedRequestedPortId =
1107 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1108 *selectedDeviceId = sanitizedRequestedPortId;
1109
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001111 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001112 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 if (status != NO_ERROR) {
1114 return status;
1115 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001116 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001117 if (secondaryOutputs != nullptr) {
1118 for (auto &secondaryMix : secondaryMixes) {
1119 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1120 if (outputDesc != nullptr &&
1121 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1122 secondaryOutputs->push_back(outputDesc->mIoHandle);
1123 weakSecondaryOutputDescs.push_back(outputDesc);
1124 }
1125 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001126 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001127
Eric Laurent8fc147b2018-07-22 19:13:55 -07001128 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001129 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001130 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001131 };
jiabin4ef93452019-09-10 14:29:54 -07001132 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001133
Eric Laurentc209fe42020-06-05 18:11:23 -07001134 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001135 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001137 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001138 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001139 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001141 std::move(weakSecondaryOutputDescs),
1142 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001143 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001144
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001145 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1146 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001147
Eric Laurente83b55d2014-11-14 10:06:21 -08001148 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001149}
1150
Eric Laurentc529cf62020-04-17 18:19:10 -07001151status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1152 audio_session_t session,
1153 const audio_config_t *config,
1154 audio_output_flags_t flags,
1155 const DeviceVector &devices,
1156 audio_io_handle_t *output) {
1157
1158 *output = AUDIO_IO_HANDLE_NONE;
1159
1160 // skip direct output selection if the request can obviously be attached to a mixed output
1161 // and not explicitly requested
1162 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1163 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1164 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1165 return NAME_NOT_FOUND;
1166 }
1167
1168 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1169 // This prevents creating an offloaded track and tearing it down immediately after start
1170 // when audioflinger detects there is an active non offloadable effect.
1171 // FIXME: We should check the audio session here but we do not have it in this context.
1172 // This may prevent offloading in rare situations where effects are left active by apps
1173 // in the background.
1174 sp<IOProfile> profile;
1175 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1176 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1177 profile = getProfileForOutput(
1178 devices, config->sample_rate, config->format, config->channel_mask,
1179 flags, true /* directOnly */);
1180 }
1181
1182 if (profile == nullptr) {
1183 return NAME_NOT_FOUND;
1184 }
1185
1186 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1187 for (size_t i = 0; i < mOutputs.size(); i++) {
1188 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1189 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1190 // reuse direct output if currently open by the same client
1191 // and configured with same parameters
1192 if ((config->sample_rate == desc->getSamplingRate()) &&
1193 (config->format == desc->getFormat()) &&
1194 (config->channel_mask == desc->getChannelMask()) &&
1195 (session == desc->mDirectClientSession)) {
1196 desc->mDirectOpenCount++;
1197 ALOGI("%s reusing direct output %d for session %d", __func__,
1198 mOutputs.keyAt(i), session);
1199 *output = mOutputs.keyAt(i);
1200 return NO_ERROR;
1201 }
1202 }
1203 }
1204
1205 if (!profile->canOpenNewIo()) {
1206 return NAME_NOT_FOUND;
1207 }
1208
1209 sp<SwAudioOutputDescriptor> outputDesc =
1210 new SwAudioOutputDescriptor(profile, mpClientInterface);
1211
1212 String8 address = getFirstDeviceAddress(devices);
1213
1214 // MSD patch may be using the only output stream that can service this request. Release
1215 // MSD patch to prioritize this request over any active output on MSD.
1216 AudioPatchCollection msdPatches = getMsdPatches();
1217 for (size_t i = 0; i < msdPatches.size(); i++) {
1218 const auto& patch = msdPatches[i];
1219 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1220 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1221 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1222 devices.containsDeviceWithType(sink->ext.device.type) &&
1223 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1224 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1225 releaseAudioPatch(patch->getHandle(), mUidCached);
1226 break;
1227 }
1228 }
1229 }
1230
1231 status_t status = outputDesc->open(config, devices, stream, flags, output);
1232
1233 // only accept an output with the requested parameters
1234 if (status != NO_ERROR ||
1235 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1236 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1237 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1238 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1239 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1240 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1241 config->channel_mask, outputDesc->getChannelMask());
1242 if (*output != AUDIO_IO_HANDLE_NONE) {
1243 outputDesc->close();
1244 }
1245 // fall back to mixer output if possible when the direct output could not be open
1246 if (audio_is_linear_pcm(config->format) &&
1247 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1248 return NAME_NOT_FOUND;
1249 }
1250 *output = AUDIO_IO_HANDLE_NONE;
1251 return BAD_VALUE;
1252 }
1253 outputDesc->mDirectOpenCount = 1;
1254 outputDesc->mDirectClientSession = session;
1255
1256 addOutput(*output, outputDesc);
1257 mPreviousOutputs = mOutputs;
1258 ALOGV("%s returns new direct output %d", __func__, *output);
1259 mpClientInterface->onAudioPortListUpdate();
1260 return NO_ERROR;
1261}
1262
François Gaffie11d30102018-11-02 16:09:09 +01001263audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1264 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001265 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001266 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001267 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001268 audio_output_flags_t *flags,
1269 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001270{
Andy Hungc88b0642018-04-27 15:42:35 -07001271 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001272
jiabine375d412019-02-26 12:54:53 -08001273 // Discard haptic channel mask when forcing muting haptic channels.
1274 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001275 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1276 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001277
Eric Laurente552edb2014-03-10 17:42:56 -07001278 // open a direct output if required by specified parameters
1279 //force direct flag if offload flag is set: offloading implies a direct output stream
1280 // and all common behaviors are driven by checking only the direct flag
1281 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001282 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1283 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001284 }
Nadav Bar766fb022018-01-07 12:18:03 +02001285 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1286 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001287 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001288 // only allow deep buffering for music stream type
1289 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001290 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001291 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001292 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001293 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1294 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001295 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001296 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001297 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001298 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001299 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001300 audio_is_linear_pcm(config->format) &&
1301 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001302 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001303 AUDIO_OUTPUT_FLAG_DIRECT);
1304 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001305 }
Eric Laurente552edb2014-03-10 17:42:56 -07001306
Eric Laurentc529cf62020-04-17 18:19:10 -07001307 audio_config_t directConfig = *config;
1308 directConfig.channel_mask = channelMask;
1309 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1310 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001311 return output;
1312 }
1313
Eric Laurent14cbfca2016-03-17 09:42:16 -07001314 // A request for HW A/V sync cannot fallback to a mixed output because time
1315 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001316 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001317 return AUDIO_IO_HANDLE_NONE;
1318 }
1319
Eric Laurente552edb2014-03-10 17:42:56 -07001320 // ignoring channel mask due to downmix capability in mixer
1321
1322 // open a non direct output
1323
1324 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001325 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001326 // get which output is suitable for the specified stream. The actual
1327 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001328 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001329
Eric Laurent8838a382014-09-08 16:44:28 -07001330 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001331 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001332 output = selectOutput(
1333 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001334 }
François Gaffie11d30102018-11-02 16:09:09 +01001335 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001336 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001337 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001338
Eric Laurente552edb2014-03-10 17:42:56 -07001339 return output;
1340}
1341
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001342sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001343 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1344 mAvailableInputDevices);
1345 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1346}
1347
1348DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1349 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1350 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001351}
1352
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001353const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1354 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001355 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1356 if (msdModule != 0) {
1357 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1358 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1359 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1360 const struct audio_port_config *source = &patch->mPatch.sources[j];
1361 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1362 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001363 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001364 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 }
1366 }
1367 }
1368 return msdPatches;
1369}
1370
François Gaffie11d30102018-11-02 16:09:09 +01001371status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001372 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1373{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001374 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 if (msdModule == nullptr) {
1376 ALOGE("%s() unable to get MSD module", __func__);
1377 return NO_INIT;
1378 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001379 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001380 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001381 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001382 return NO_INIT;
1383 }
1384 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1385 if (inputProfiles.isEmpty()) {
1386 ALOGE("%s() no input profiles for MSD module", __func__);
1387 return NO_INIT;
1388 }
1389 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1390 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001391 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001392 return NO_INIT;
1393 }
1394 AudioProfileVector msdProfiles;
1395 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1396 for (const auto &inProfile : inputProfiles) {
1397 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001398 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001399 }
1400 }
1401 AudioProfileVector deviceProfiles;
1402 for (const auto &outProfile : outputProfiles) {
1403 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001404 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001405 }
1406 }
1407 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001408 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001409 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001410 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001412 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1413 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001414 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415 }
1416 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1417 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1418 sinkConfig->format = bestSinkConfig.format;
1419 // For encoded streams force direct flag to prevent downstream mixing.
1420 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1421 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001422 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1423 // For formats compatible with IEC61937 encapsulation, assume that
1424 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1425 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1426 // raw and IEC61937 framed streams.
1427 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1428 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1429 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001430 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1431 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1432 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1433 sourceConfig->format = bestSinkConfig.format;
1434 // Copy input stream directly without any processing (e.g. resampling).
1435 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1436 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1437 if (hwAvSync) {
1438 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1439 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1440 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1441 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1442 }
1443 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1444 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1445 sinkConfig->config_mask |= config_mask;
1446 sourceConfig->config_mask |= config_mask;
1447 return NO_ERROR;
1448}
1449
François Gaffie11d30102018-11-02 16:09:09 +01001450PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001451{
1452 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001453 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001454 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1455 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1456 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1457 // For now, we just forcefully try with HwAvSync first.
1458 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1459 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1460 getBestMsdAudioProfileFor(
1461 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1462 if (res == NO_ERROR) {
1463 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1464 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1465 }
1466 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1467 " supporting PCM format conversion.", __func__);
1468 return patchBuilder;
1469}
1470
François Gaffie11d30102018-11-02 16:09:09 +01001471status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1472 sp<DeviceDescriptor> device = outputDevice;
1473 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 // Use media strategy for unspecified output device. This should only
1475 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1476 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001477 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1478 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001479 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1480 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001481 }
François Gaffie11d30102018-11-02 16:09:09 +01001482 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1483 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001484 const struct audio_patch* patch = patchBuilder.patch();
1485 const AudioPatchCollection msdPatches = getMsdPatches();
1486 if (!msdPatches.isEmpty()) {
1487 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1488 "The current MSD prototype only supports one output patch");
1489 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1490 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1491 return NO_ERROR;
1492 }
François Gaffieafd4cea2019-11-18 15:50:22 +01001493 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001494 }
1495 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1496 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1497 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1498 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001499 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1500 device->toString().c_str(), patch->sources[0].format,
1501 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001502 return status;
1503}
1504
Eric Laurente0720872014-03-11 09:30:41 -07001505audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001506 audio_output_flags_t flags,
1507 audio_format_t format,
1508 audio_channel_mask_t channelMask,
1509 uint32_t samplingRate,
1510 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001511{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001512 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1513 "%s called with format %#x", __func__, format);
1514
jiabinebb6af42020-06-09 17:31:17 -07001515 // Return the output that haptic-generating attached to when 1) session id is specified,
1516 // 2) haptic-generating effect exists for given session id and 3) the output that
1517 // haptic-generating effect attached to is in given outputs.
1518 if (sessionId != AUDIO_SESSION_NONE) {
1519 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1520 sessionId, FX_IID_HAPTICGENERATOR);
1521 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1522 return hapticGeneratingOutput;
1523 }
1524 }
1525
Eric Laurent16c66dd2019-05-01 17:54:10 -07001526 // Flags disqualifying an output: the match must happen before calling selectOutput()
1527 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1528 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1529
1530 // Flags expressing a functional request: must be honored in priority over
1531 // other criteria
1532 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1533 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1534 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1535 // Flags expressing a performance request: have lower priority than serving
1536 // requested sampling rate or channel mask
1537 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1538 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1539 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1540
1541 const audio_output_flags_t functionalFlags =
1542 (audio_output_flags_t)(flags & kFunctionalFlags);
1543 const audio_output_flags_t performanceFlags =
1544 (audio_output_flags_t)(flags & kPerformanceFlags);
1545
1546 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1547
Eric Laurente552edb2014-03-10 17:42:56 -07001548 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001549 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001550 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001551 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001552 // 2: the output with the highest number of requested functional flags
1553 // 3: the output supporting the exact channel mask
1554 // 4: the output with a higher channel count than requested
1555 // 5: the output with a higher sampling rate than requested
1556 // 6: the output with the highest number of requested performance flags
1557 // 7: the output with the bit depth the closest to the requested one
1558 // 8: the primary output
1559 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Eric Laurent16c66dd2019-05-01 17:54:10 -07001561 // matching criteria values in priority order for best matching output so far
1562 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001563
Eric Laurent16c66dd2019-05-01 17:54:10 -07001564 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1565 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1566 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001567
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001568 for (audio_io_handle_t output : outputs) {
1569 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001570 // matching criteria values in priority order for current output
1571 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001572
Eric Laurent16c66dd2019-05-01 17:54:10 -07001573 if (outputDesc->isDuplicated()) {
1574 continue;
1575 }
1576 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1577 continue;
1578 }
Eric Laurent8838a382014-09-08 16:44:28 -07001579
Eric Laurent16c66dd2019-05-01 17:54:10 -07001580 // If haptic channel is specified, use the haptic output if present.
1581 // When using haptic output, same audio format and sample rate are required.
1582 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001583 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001584 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1585 continue;
1586 }
1587 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001588 && format == outputDesc->getFormat()
1589 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001590 currentMatchCriteria[0] = outputHapticChannelCount;
1591 }
1592
1593 // functional flags match
1594 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1595
1596 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001597 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1598 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001599 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1600 channelCount <= outputChannelCount) {
1601 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001602 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1603 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001604 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001605 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001606 currentMatchCriteria[3] = outputChannelCount;
1607 }
1608
1609 // sampling rate match
1610 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001611 samplingRate <= outputDesc->getSamplingRate()) {
1612 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001613 }
1614
1615 // performance flags match
1616 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1617
1618 // format match
1619 if (format != AUDIO_FORMAT_INVALID) {
1620 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001621 PolicyAudioPort::kFormatDistanceMax -
1622 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001623 }
1624
1625 // primary output match
1626 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1627
1628 // compare match criteria by priority then value
1629 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1630 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1631 bestMatchCriteria = currentMatchCriteria;
1632 bestOutput = output;
1633
1634 std::stringstream result;
1635 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1636 std::ostream_iterator<int>(result, " "));
1637 ALOGV("%s new bestOutput %d criteria %s",
1638 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001639 }
1640 }
1641
Eric Laurent16c66dd2019-05-01 17:54:10 -07001642 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001643}
1644
Eric Laurent8fc147b2018-07-22 19:13:55 -07001645status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001646{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001647 ALOGV("%s portId %d", __FUNCTION__, portId);
1648
1649 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1650 if (outputDesc == 0) {
1651 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001652 return BAD_VALUE;
1653 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001654 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001655
Eric Laurent8fc147b2018-07-22 19:13:55 -07001656 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001657 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001658
Eric Laurent733ce942017-12-07 12:18:25 -08001659 status_t status = outputDesc->start();
1660 if (status != NO_ERROR) {
1661 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001662 }
1663
Eric Laurent97ac8712018-07-27 18:59:02 -07001664 uint32_t delayMs;
1665 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001666
1667 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001668 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001669 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001670 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001671 if (delayMs != 0) {
1672 usleep(delayMs * 1000);
1673 }
1674
1675 return status;
1676}
1677
Eric Laurent97ac8712018-07-27 18:59:02 -07001678status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1679 const sp<TrackClientDescriptor>& client,
1680 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001681{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001682 // cannot start playback of STREAM_TTS if any other output is being used
1683 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001684
1685 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001686 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001687 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001688 auto clientStrategy = client->strategy();
1689 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001690 if (stream == AUDIO_STREAM_TTS) {
1691 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001692 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001693 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001694 return INVALID_OPERATION;
1695 } else {
1696 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1697 }
1698 } else {
1699 // some playback other than beacon starts
1700 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1701 }
1702
Eric Laurent77305a62016-07-25 16:39:22 -07001703 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001704 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001705 bool force = !outputDesc->isActive() &&
1706 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001707
François Gaffie11d30102018-11-02 16:09:09 +01001708 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001709 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001710 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001711 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001712 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001713 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001714 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001715 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001716 } else {
1717 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001718 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001719 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1720 AUDIO_FORMAT_DEFAULT);
1721 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1722 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001723 }
1724
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001725 // requiresMuteCheck is false when we can bypass mute strategy.
1726 // It covers a common case when there is no materially active audio
1727 // and muting would result in unnecessary delay and dropped audio.
1728 const uint32_t outputLatencyMs = outputDesc->latency();
1729 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1730
Eric Laurente552edb2014-03-10 17:42:56 -07001731 // increment usage count for this stream on the requested output:
1732 // NOTE that the usage count is the same for duplicated output and hardware output which is
1733 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001734 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001735
1736 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001737 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1738 client->isPreferredDeviceForExclusiveUse()) {
1739 // Preferred device may be exclusive, use only if no other active clients on this output
1740 devices = DeviceVector(
1741 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1742 } else {
1743 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1744 }
François Gaffie11d30102018-11-02 16:09:09 +01001745 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001746 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 }
1748 }
Eric Laurente552edb2014-03-10 17:42:56 -07001749
François Gaffiec005e562018-11-06 15:04:49 +01001750 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001751 selectOutputForMusicEffects();
1752 }
1753
François Gaffie1c878552018-11-22 16:53:21 +01001754 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001755 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001756 if (devices.isEmpty()) {
1757 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001758 }
François Gaffiec005e562018-11-06 15:04:49 +01001759 bool shouldWait =
1760 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1761 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1762 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001763 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001764 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001765 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001766 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001767 // An output has a shared device if
1768 // - managed by the same hw module
1769 // - supports the currently selected device
1770 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001771 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001772
Eric Laurent77305a62016-07-25 16:39:22 -07001773 // force a device change if any other output is:
1774 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001775 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001776 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001777 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001778 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001779 // change the device currently selected by the other output.
1780 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001781 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001782 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001783 force = true;
1784 }
1785 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001786 // a notification so that audio focus effect can propagate, or that a mute/unmute
1787 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001788 const uint32_t latencyMs = desc->latency();
1789 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1790
1791 if (shouldWait && isActive && (waitMs < latencyMs)) {
1792 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001793 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001794
1795 // Require mute check if another output is on a shared device
1796 // and currently active to have proper drain and avoid pops.
1797 // Note restoring AudioTracks onto this output needs to invoke
1798 // a volume ramp if there is no mute.
1799 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001800 }
1801 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001802
1803 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001804 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001805
Eric Laurente552edb2014-03-10 17:42:56 -07001806 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001807 auto &curves = getVolumeCurves(client->attributes());
1808 checkAndSetVolume(curves, client->volumeSource(),
1809 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001810 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001811 outputDesc->devices().types(), 0 /*delay*/,
1812 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001813
1814 // update the outputs if starting an output with a stream that can affect notification
1815 // routing
1816 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001817
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001818 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001819 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001820 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1821 }
Eric Laurentdc462862016-07-19 12:29:53 -07001822
1823 if (waitMs > muteWaitMs) {
1824 *delayMs = waitMs - muteWaitMs;
1825 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001826
1827 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1828 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1829 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1830 // change occurs after the MixerThread starts and causes a stream volume
1831 // glitch.
1832 //
1833 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001834 }
Eric Laurentdc462862016-07-19 12:29:53 -07001835
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001836 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001837 mEngine->getForceUse(
1838 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001839 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001840 }
1841
Eric Laurent97ac8712018-07-27 18:59:02 -07001842 // Automatically enable the remote submix input when output is started on a re routing mix
1843 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001844 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1845 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001846 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1847 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1848 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001849 "remote-submix",
1850 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001851 }
1852
Eric Laurente552edb2014-03-10 17:42:56 -07001853 return NO_ERROR;
1854}
1855
Eric Laurent8fc147b2018-07-22 19:13:55 -07001856status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001857{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001858 ALOGV("%s portId %d", __FUNCTION__, portId);
1859
1860 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1861 if (outputDesc == 0) {
1862 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001863 return BAD_VALUE;
1864 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001865 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001866
Eric Laurent97ac8712018-07-27 18:59:02 -07001867 ALOGV("stopOutput() output %d, stream %d, session %d",
1868 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurent97ac8712018-07-27 18:59:02 -07001870 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001871
Eric Laurent733ce942017-12-07 12:18:25 -08001872 if (status == NO_ERROR ) {
1873 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001874 }
1875 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001876}
1877
Eric Laurent97ac8712018-07-27 18:59:02 -07001878status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1879 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001880{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001881 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001882 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001883 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001884
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001885 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1886
François Gaffie1c878552018-11-22 16:53:21 +01001887 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1888 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001889 // Automatically disable the remote submix input when output is stopped on a
1890 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001891 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001892 if (isSingleDeviceType(
1893 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001894 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001895 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001896 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1897 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001898 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001899 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001900 }
1901 }
1902 bool forceDeviceUpdate = false;
1903 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001904 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001905 forceDeviceUpdate = true;
1906 }
1907
Eric Laurente552edb2014-03-10 17:42:56 -07001908 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001909 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001910
Eric Laurente552edb2014-03-10 17:42:56 -07001911 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001912 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001913 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001914 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001915 // delay the device switch by twice the latency because stopOutput() is executed when
1916 // the track stop() command is received and at that time the audio track buffer can
1917 // still contain data that needs to be drained. The latency only covers the audio HAL
1918 // and kernel buffers. Also the latency does not always include additional delay in the
1919 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001920 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001921
1922 // force restoring the device selection on other active outputs if it differs from the
1923 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001924 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001925 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001927 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001928 desc->isActive() &&
1929 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001930 (newDevices != desc->devices())) {
1931 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1932 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001933
François Gaffie11d30102018-11-02 16:09:09 +01001934 setOutputDevices(desc, newDevices2, force, delayMs);
1935
Eric Laurent57de36c2016-09-28 16:59:11 -07001936 // re-apply device specific volume if not done by setOutputDevice()
1937 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001938 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001939 }
Eric Laurente552edb2014-03-10 17:42:56 -07001940 }
1941 }
1942 // update the outputs if stopping one with a stream that can affect notification routing
1943 handleNotificationRoutingForStream(stream);
1944 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001945
1946 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1947 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001948 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001949 }
1950
François Gaffiec005e562018-11-06 15:04:49 +01001951 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001952 selectOutputForMusicEffects();
1953 }
Eric Laurente552edb2014-03-10 17:42:56 -07001954 return NO_ERROR;
1955 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001956 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001957 return INVALID_OPERATION;
1958 }
1959}
1960
jiabinbce0c1d2020-10-05 11:20:18 -07001961bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001962{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001963 ALOGV("%s portId %d", __FUNCTION__, portId);
1964
1965 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1966 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001967 // If an output descriptor is closed due to a device routing change,
1968 // then there are race conditions with releaseOutput from tracks
1969 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1970 // destroyed shortly thereafter.
1971 //
1972 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001973 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001974 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001975 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976
1977 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001978
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301979 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
1980 if (outputDesc->isClientActive(client)) {
1981 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
1982 stopOutput(portId);
1983 }
1984
Eric Laurent8fc147b2018-07-22 19:13:55 -07001985 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1986 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001987 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001988 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07001989 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07001990 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001991 if (--outputDesc->mDirectOpenCount == 0) {
1992 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001993 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001994 }
1995 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05301996
Andy Hung39efb7a2018-09-26 15:39:28 -07001997 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07001998 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
1999 // The output is pending reopened to query dynamic profiles and
2000 // there is no active clients
2001 closeOutput(outputDesc->mIoHandle);
2002 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2003 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2004 if (newOutputDesc == nullptr) {
2005 ALOGE("%s failed to open output", __func__);
2006 }
2007 return true;
2008 }
2009 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002010}
2011
Eric Laurentcaf7f482014-11-25 17:50:47 -08002012status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2013 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002014 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002015 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002016 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002017 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002018 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002019 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002020 input_type_t *inputType,
2021 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002022{
François Gaffiec005e562018-11-06 15:04:49 +01002023 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2024 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2025 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002026
Eric Laurentad2e7b92017-09-14 20:06:42 -07002027 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002028 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002029 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002030 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002031 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002032 sp<AudioInputDescriptor> inputDesc;
2033 sp<RecordClientDescriptor> clientDesc;
2034 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036
2037 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2038 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2039 return INVALID_OPERATION;
2040 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002041
Francois Gaffie716e1432019-01-14 16:58:59 +01002042 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2043 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002044 }
2045
Paul McLean466dc8e2015-04-17 13:15:36 -06002046 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002047 sp<DeviceDescriptor> explicitRoutingDevice =
2048 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002049
Eric Laurentad2e7b92017-09-14 20:06:42 -07002050 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2051 // possible
2052 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2053 *input != AUDIO_IO_HANDLE_NONE) {
2054 ssize_t index = mInputs.indexOfKey(*input);
2055 if (index < 0) {
2056 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2057 status = BAD_VALUE;
2058 goto error;
2059 }
2060 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061 RecordClientVector clients = inputDesc->getClientsForSession(session);
2062 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002063 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2064 status = BAD_VALUE;
2065 goto error;
2066 }
2067 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2068 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002069 // corresponds to a new client and is only permitted from the same UID.
2070 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 if (clients.size() > 1) {
2072 for (const auto& client : clients) {
2073 // The client map is ordered by key values (portId) and portIds are allocated
2074 // incrementaly. So the first client in this list is the one opened by audio flinger
2075 // when the mmap stream is created and should be ignored as it does not correspond
2076 // to an actual client
2077 if (client == *clients.cbegin()) {
2078 continue;
2079 }
2080 if (uid != client->uid() && !client->isSilenced()) {
2081 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2082 uid, client->portId(), client->uid());
2083 status = INVALID_OPERATION;
2084 goto error;
2085 }
Eric Laurent331679c2018-04-16 17:03:16 -07002086 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002087 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002088 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002089 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002090
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002092 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002093 }
2094
2095 *input = AUDIO_IO_HANDLE_NONE;
2096 *inputType = API_INPUT_INVALID;
2097
Francois Gaffie716e1432019-01-14 16:58:59 +01002098 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002099
Francois Gaffie716e1432019-01-14 16:58:59 +01002100 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2101 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2102 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002103 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002104 ALOGW("%s could not find input mix for attr %s",
2105 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002106 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002107 }
jiabinc1de2df2019-05-07 14:26:40 -07002108 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2109 String8(attr->tags + strlen("addr=")),
2110 AUDIO_FORMAT_DEFAULT);
2111 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002112 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002113 __func__, attributes.source, attributes.tags);
2114 status = BAD_VALUE;
2115 goto error;
2116 }
2117
Kevin Rocard25f9b052019-02-27 15:08:54 -08002118 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2119 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2120 } else {
2121 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002123 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002124 if (explicitRoutingDevice != nullptr) {
2125 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002126 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002127 // Prevent from storing invalid requested device id in clients
2128 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002129 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002130 }
François Gaffie11d30102018-11-02 16:09:09 +01002131 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002132 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002133 status = BAD_VALUE;
2134 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002135 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002136 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002137 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2138 // there is an external policy, but this input is attached to a mix of recorders,
2139 // meaning it receives audio injected into the framework, so the recorder doesn't
2140 // know about it and is therefore considered "legacy"
2141 *inputType = API_INPUT_LEGACY;
2142 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002143 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002144 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002145 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002146 } else {
2147 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002148 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002149
Eric Laurent599c7582015-12-07 18:05:55 -08002150 }
2151
François Gaffiec005e562018-11-06 15:04:49 +01002152 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002153 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002154 status = INVALID_OPERATION;
2155 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002156 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002157
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158exit:
2159
François Gaffiec005e562018-11-06 15:04:49 +01002160 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2161 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002162
Francois Gaffie716e1432019-01-14 16:58:59 +01002163 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002164 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002165 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166
Mikhail Naganov2996f672019-04-18 12:29:59 -07002167 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002168 requestedDeviceId, attributes.source, flags,
2169 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002170 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002171 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002172
2173 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2174 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002175
Eric Laurent599c7582015-12-07 18:05:55 -08002176 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002177
2178error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002179 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002180}
2181
2182
François Gaffie11d30102018-11-02 16:09:09 +01002183audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002184 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002185 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002186 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002187 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002188 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002189{
2190 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002191 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002192 bool isSoundTrigger = false;
2193
François Gaffiec005e562018-11-06 15:04:49 +01002194 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002195 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2196 if (index >= 0) {
2197 input = mSoundTriggerSessions.valueFor(session);
2198 isSoundTrigger = true;
2199 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2200 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2201 } else {
2202 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002203 }
François Gaffiec005e562018-11-06 15:04:49 +01002204 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002205 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002206 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002207 }
2208
Andy Hungf129b032015-04-07 13:45:50 -07002209 // find a compatible input profile (not necessarily identical in parameters)
2210 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002211 // sampling rate and flags may be updated by getInputProfile
2212 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2213 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002214 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002215 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002216 audio_input_flags_t profileFlags = flags;
2217 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002218 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002219 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002220 profileFlags);
2221 if (profile != 0) {
2222 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002223 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2224 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002225 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2226 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2227 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002228 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2229 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2230 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002231 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002232 }
Eric Laurente552edb2014-03-10 17:42:56 -07002233 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002234 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002235 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002236 if (samplingRate == 0) {
2237 samplingRate = profileSamplingRate;
2238 }
Eric Laurente552edb2014-03-10 17:42:56 -07002239
Eric Laurent322b4d22015-04-03 15:57:54 -07002240 if (profile->getModuleHandle() == 0) {
2241 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002242 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002243 }
2244
Eric Laurent3974e3b2017-12-07 17:58:43 -08002245 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002246 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002247 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002248 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002249 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002250 continue;
2251 }
2252 // if sound trigger, reuse input if used by other sound trigger on same session
2253 // else
2254 // reuse input if active client app is not in IDLE state
2255 //
2256 RecordClientVector clients = desc->clientsList();
2257 bool doClose = false;
2258 for (const auto& client : clients) {
2259 if (isSoundTrigger != client->isSoundTrigger()) {
2260 continue;
2261 }
2262 if (client->isSoundTrigger()) {
2263 if (session == client->session()) {
2264 return desc->mIoHandle;
2265 }
2266 continue;
2267 }
2268 if (client->active() && client->appState() != APP_STATE_IDLE) {
2269 return desc->mIoHandle;
2270 }
2271 doClose = true;
2272 }
2273 if (doClose) {
2274 closeInput(desc->mIoHandle);
2275 } else {
2276 i++;
2277 }
2278 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002279 }
2280
Eric Laurentfe231122017-11-17 17:48:06 -08002281 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002282
Eric Laurentfe231122017-11-17 17:48:06 -08002283 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2284 lConfig.sample_rate = profileSamplingRate;
2285 lConfig.channel_mask = profileChannelMask;
2286 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002287
François Gaffie11d30102018-11-02 16:09:09 +01002288 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002289
2290 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002291 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002292 (profileSamplingRate != lConfig.sample_rate) ||
2293 !audio_formats_match(profileFormat, lConfig.format) ||
2294 (profileChannelMask != lConfig.channel_mask)) {
2295 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002296 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002297 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002298 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002299 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002300 }
Eric Laurent599c7582015-12-07 18:05:55 -08002301 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002302 }
2303
Eric Laurentc722f302014-12-10 11:21:49 -08002304 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002305
Eric Laurent599c7582015-12-07 18:05:55 -08002306 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002307 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002308
Eric Laurent599c7582015-12-07 18:05:55 -08002309 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002310}
2311
Eric Laurent4eb58f12018-12-07 16:41:02 -08002312status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002313{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002314 ALOGV("%s portId %d", __FUNCTION__, portId);
2315
2316 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2317 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002318 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002319 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002320 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002321 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002322 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002323 if (client->active()) {
2324 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2325 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002326 }
2327
Eric Laurent8f42ea12018-08-08 09:08:25 -07002328 audio_session_t session = client->session();
2329
Eric Laurent4eb58f12018-12-07 16:41:02 -08002330 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002331
Eric Laurent4eb58f12018-12-07 16:41:02 -08002332 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002333
Eric Laurent4eb58f12018-12-07 16:41:02 -08002334 status_t status = inputDesc->start();
2335 if (status != NO_ERROR) {
2336 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002337 }
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002339 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002340 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002341 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002342
Eric Laurent8f42ea12018-08-08 09:08:25 -07002343 // indicate active capture to sound trigger service if starting capture from a mic on
2344 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002345 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002346 if (device != nullptr) {
2347 status = setInputDevice(input, device, true /* force */);
2348 } else {
2349 ALOGW("%s no new input device can be found for descriptor %d",
2350 __FUNCTION__, inputDesc->getId());
2351 status = BAD_VALUE;
2352 }
Eric Laurente552edb2014-03-10 17:42:56 -07002353
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002354 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002355 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002356 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002357 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002358 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2359 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002360 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002361 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002362
François Gaffie11d30102018-11-02 16:09:09 +01002363 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2364 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002365 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002366 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002367 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002368
Eric Laurent8f42ea12018-08-08 09:08:25 -07002369 // automatically enable the remote submix output when input is started if not
2370 // used by a policy mix of type MIX_TYPE_RECORDERS
2371 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002372 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002373 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002374 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002375 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002376 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2377 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002378 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002379 if (address != "") {
2380 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2381 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002382 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002383 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002384 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002385 } else if (status != NO_ERROR) {
2386 // Restore client activity state.
2387 inputDesc->setClientActive(client, false);
2388 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002389 }
2390
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002391 ALOGV("%s input %d source = %d status = %d exit",
2392 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002394 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002395}
2396
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002398{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002399 ALOGV("%s portId %d", __FUNCTION__, portId);
2400
2401 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2402 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002403 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002404 return BAD_VALUE;
2405 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002406 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002407 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002408 if (!client->active()) {
2409 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002410 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002411 }
2412
Eric Laurent8f42ea12018-08-08 09:08:25 -07002413 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002414
Eric Laurent8f42ea12018-08-08 09:08:25 -07002415 inputDesc->stop();
2416 if (inputDesc->isActive()) {
2417 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2418 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002419 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002420 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002421 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002422 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2423 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002424 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002425 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002426
2427 // automatically disable the remote submix output when input is stopped if not
2428 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002429 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002430 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002431 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002432 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002433 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2434 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002435 }
2436 if (address != "") {
2437 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2438 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002439 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002440 }
2441 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002442 resetInputDevice(input);
2443
2444 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2445 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002446 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2447 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002448 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002449 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002450 }
2451 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002452 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002453 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002454}
2455
Eric Laurent8fc147b2018-07-22 19:13:55 -07002456void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002457{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002458 ALOGV("%s portId %d", __FUNCTION__, portId);
2459
2460 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2461 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002462 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002463 return;
2464 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002465 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002466 audio_io_handle_t input = inputDesc->mIoHandle;
2467
Eric Laurent8f42ea12018-08-08 09:08:25 -07002468 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002469
Andy Hung39efb7a2018-09-26 15:39:28 -07002470 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002471
Andy Hung39efb7a2018-09-26 15:39:28 -07002472 if (inputDesc->getClientCount() > 0) {
2473 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002474 return;
2475 }
2476
Eric Laurent05b90f82014-08-27 15:32:29 -07002477 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002478 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002480}
2481
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002483{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002484 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002485
2486 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002487 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002488 }
2489}
2490
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2492{
2493 stopInput(portId);
2494 releaseInput(portId);
2495}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002496
Eric Laurent0dd51852019-04-19 18:18:58 -07002497void AudioPolicyManager::checkCloseInputs() {
2498 // After connecting or disconnecting an input device, close input if:
2499 // - it has no client (was just opened to check profile) OR
2500 // - none of its supported devices are connected anymore OR
2501 // - one of its clients cannot be routed to one of its supported
2502 // devices anymore. Otherwise update device selection
2503 std::vector<audio_io_handle_t> inputsToClose;
2504 for (size_t i = 0; i < mInputs.size(); i++) {
2505 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2506 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002507 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002508 inputsToClose.push_back(mInputs.keyAt(i));
2509 } else {
2510 bool close = false;
2511 for (const auto& client : input->clientsList()) {
2512 sp<DeviceDescriptor> device =
2513 mEngine->getInputDeviceForAttributes(client->attributes());
2514 if (!input->supportedDevices().contains(device)) {
2515 close = true;
2516 break;
2517 }
2518 }
2519 if (close) {
2520 inputsToClose.push_back(mInputs.keyAt(i));
2521 } else {
2522 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2523 }
2524 }
2525 }
2526
2527 for (const audio_io_handle_t handle : inputsToClose) {
2528 ALOGV("%s closing input %d", __func__, handle);
2529 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002530 }
Eric Laurentd4692962014-05-05 18:13:44 -07002531}
2532
François Gaffie251c7f02018-11-07 10:41:08 +01002533void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002534{
2535 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002536 if (indexMin < 0 || indexMax < 0) {
2537 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2538 return;
2539 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002540 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002541
2542 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002543 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2544 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002545 continue;
2546 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002547 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002548 }
Eric Laurente552edb2014-03-10 17:42:56 -07002549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002552 int index,
2553 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002554{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002555 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002556 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2557 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2558 return NO_ERROR;
2559 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002560 ALOGV("%s: stream %s attributes=%s", __func__,
2561 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002562 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002563}
2564
Eric Laurente0720872014-03-11 09:30:41 -07002565status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002566 int *index,
2567 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002568{
François Gaffiec005e562018-11-06 15:04:49 +01002569 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2570 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002571 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002572 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002573 deviceTypes = mEngine->getOutputDevicesForStream(
2574 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002575 }
jiabin9a3361e2019-10-01 09:38:30 -07002576 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002577}
2578
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002579status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002580 int index,
2581 audio_devices_t device)
2582{
2583 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002584 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2585 if (group == VOLUME_GROUP_NONE) {
2586 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002587 return BAD_VALUE;
2588 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002589 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002590 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002591 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002592 VolumeSource vs = toVolumeSource(group);
2593 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2594
2595 status = setVolumeCurveIndex(index, device, curves);
2596 if (status != NO_ERROR) {
2597 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2598 return status;
2599 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002600
jiabin9a3361e2019-10-01 09:38:30 -07002601 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002602 auto curCurvAttrs = curves.getAttributes();
2603 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2604 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002605 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002606 } else if (!curves.getStreamTypes().empty()) {
2607 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002608 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002609 } else {
2610 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2611 return BAD_VALUE;
2612 }
jiabin9a3361e2019-10-01 09:38:30 -07002613 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2614 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002615
François Gaffiecfe17322018-11-07 13:41:29 +01002616 // update volume on all outputs and streams matching the following:
2617 // - The requested stream (or a stream matching for volume control) is active on the output
2618 // - The device (or devices) selected by the engine for this stream includes
2619 // the requested device
2620 // - For non default requested device, currently selected device on the output is either the
2621 // requested device or one of the devices selected by the engine for this stream
2622 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2623 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002624 for (size_t i = 0; i < mOutputs.size(); i++) {
2625 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002626 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002627
jiabin9a3361e2019-10-01 09:38:30 -07002628 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2629 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002630 }
François Gaffieed91f582020-01-31 10:35:37 +01002631 if (!(desc->isActive(vs) || isInCall())) {
2632 continue;
2633 }
2634 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2635 curDevices.find(device) == curDevices.end()) {
2636 continue;
2637 }
2638 bool applyVolume = false;
2639 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2640 curSrcDevices.insert(device);
2641 applyVolume = (curSrcDevices.find(
2642 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2643 } else {
2644 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2645 }
2646 if (!applyVolume) {
2647 continue; // next output
2648 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002649 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2650 // If a higher priority strategy is active, and the output is routed to a device with a
2651 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002652 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002653 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002654 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2655 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2656 false /*preferredDevice*/);
2657 if (activeClients.empty()) {
2658 continue;
2659 }
2660 bool isPreempted = false;
2661 bool isHigherPriority = productStrategy < strategy;
2662 for (const auto &client : activeClients) {
2663 if (isHigherPriority && (client->volumeSource() != vs)) {
2664 ALOGV("%s: Strategy=%d (\nrequester:\n"
2665 " group %d, volumeGroup=%d attributes=%s)\n"
2666 " higher priority source active:\n"
2667 " volumeGroup=%d attributes=%s) \n"
2668 " on output %zu, bailing out", __func__, productStrategy,
2669 group, group, toString(attributes).c_str(),
2670 client->volumeSource(), toString(client->attributes()).c_str(), i);
2671 applyVolume = false;
2672 isPreempted = true;
2673 break;
2674 }
2675 // However, continue for loop to ensure no higher prio clients running on output
2676 if (client->volumeSource() == vs) {
2677 applyVolume = true;
2678 }
2679 }
2680 if (isPreempted || applyVolume) {
2681 break;
2682 }
2683 }
2684 if (!applyVolume) {
2685 continue; // next output
2686 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002687 }
François Gaffieed91f582020-01-31 10:35:37 +01002688 //FIXME: workaround for truncated touch sounds
2689 // delayed volume change for system stream to be removed when the problem is
2690 // handled by system UI
2691 status_t volStatus = checkAndSetVolume(
2692 curves, vs, index, desc, curDevices,
2693 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2694 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2695 if (volStatus != NO_ERROR) {
2696 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002697 }
2698 }
François Gaffiecfe17322018-11-07 13:41:29 +01002699 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2700 return status;
2701}
2702
François Gaffieaaac0fd2018-11-22 17:56:39 +01002703status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002704 audio_devices_t device,
2705 IVolumeCurves &volumeCurves)
2706{
2707 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2708 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002709 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2710 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002711 (index > volumeCurves.getVolumeIndexMax())) {
2712 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2713 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2714 return BAD_VALUE;
2715 }
2716 if (!audio_is_output_device(device)) {
2717 return BAD_VALUE;
2718 }
2719
2720 // Force max volume if stream cannot be muted
2721 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2722
François Gaffieaaac0fd2018-11-22 17:56:39 +01002723 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002724 volumeCurves.addCurrentVolumeIndex(device, index);
2725 return NO_ERROR;
2726}
2727
2728status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2729 int &index,
2730 audio_devices_t device)
2731{
2732 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2733 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002734 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002735 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002736 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2737 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002738 }
jiabin9a3361e2019-10-01 09:38:30 -07002739 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002740}
2741
2742status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2743 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002744 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002745{
jiabin9a3361e2019-10-01 09:38:30 -07002746 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002747 return BAD_VALUE;
2748 }
jiabin9a3361e2019-10-01 09:38:30 -07002749 index = curves.getVolumeIndex(deviceTypes);
2750 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002751 return NO_ERROR;
2752}
2753
2754status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2755 int &index)
2756{
2757 index = getVolumeCurves(attr).getVolumeIndexMin();
2758 return NO_ERROR;
2759}
2760
2761status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2762 int &index)
2763{
2764 index = getVolumeCurves(attr).getVolumeIndexMax();
2765 return NO_ERROR;
2766}
2767
Eric Laurent36829f92017-04-07 19:04:42 -07002768audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002769{
2770 // select one output among several suitable for global effects.
2771 // The priority is as follows:
2772 // 1: An offloaded output. If the effect ends up not being offloadable,
2773 // AudioFlinger will invalidate the track and the offloaded output
2774 // will be closed causing the effect to be moved to a PCM output.
2775 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002776 // 3: The primary output
2777 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002778
François Gaffiec005e562018-11-06 15:04:49 +01002779 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2780 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002781 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002782
Eric Laurent36829f92017-04-07 19:04:42 -07002783 if (outputs.size() == 0) {
2784 return AUDIO_IO_HANDLE_NONE;
2785 }
Eric Laurente552edb2014-03-10 17:42:56 -07002786
Eric Laurent36829f92017-04-07 19:04:42 -07002787 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2788 bool activeOnly = true;
2789
2790 while (output == AUDIO_IO_HANDLE_NONE) {
2791 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2792 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2793 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2794
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002795 for (audio_io_handle_t output : outputs) {
2796 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002797 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002798 continue;
2799 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002800 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2801 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002802 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002803 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002804 }
2805 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002806 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002807 }
2808 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002809 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002810 }
2811 }
2812 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2813 output = outputOffloaded;
2814 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2815 output = outputDeepBuffer;
2816 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2817 output = outputPrimary;
2818 } else {
2819 output = outputs[0];
2820 }
2821 activeOnly = false;
2822 }
2823
2824 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002825 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002826 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2827 mMusicEffectOutput = output;
2828 }
2829
2830 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002831 return output;
2832}
2833
Eric Laurent36829f92017-04-07 19:04:42 -07002834audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2835{
2836 return selectOutputForMusicEffects();
2837}
2838
Eric Laurente0720872014-03-11 09:30:41 -07002839status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002840 audio_io_handle_t io,
2841 uint32_t strategy,
2842 int session,
2843 int id)
2844{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002845 if (session != AUDIO_SESSION_DEVICE) {
2846 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002847 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002848 index = mInputs.indexOfKey(io);
2849 if (index < 0) {
2850 ALOGW("registerEffect() unknown io %d", io);
2851 return INVALID_OPERATION;
2852 }
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
2854 }
François Gaffiec005e562018-11-06 15:04:49 +01002855 return mEffects.registerEffect(desc, io, session, id,
2856 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2857 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002858}
2859
Eric Laurentc241b0d2018-11-28 09:08:49 -08002860status_t AudioPolicyManager::unregisterEffect(int id)
2861{
2862 if (mEffects.getEffect(id) == nullptr) {
2863 return INVALID_OPERATION;
2864 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002865 if (mEffects.isEffectEnabled(id)) {
2866 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2867 setEffectEnabled(id, false);
2868 }
2869 return mEffects.unregisterEffect(id);
2870}
2871
2872status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2873{
2874 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2875 if (effect == nullptr) {
2876 return INVALID_OPERATION;
2877 }
2878
2879 status_t status = mEffects.setEffectEnabled(id, enabled);
2880 if (status == NO_ERROR) {
2881 mInputs.trackEffectEnabled(effect, enabled);
2882 }
2883 return status;
2884}
2885
Eric Laurent6c796322019-04-09 14:13:17 -07002886
2887status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2888{
2889 mEffects.moveEffects(ids, io);
2890 return NO_ERROR;
2891}
2892
Eric Laurentc75307b2015-03-17 15:29:32 -07002893bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2894{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002895 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002896}
2897
2898bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2899{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002900 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002901}
2902
Eric Laurente0720872014-03-11 09:30:41 -07002903bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002904{
2905 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002906 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002907 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002908 return true;
2909 }
2910 }
2911 return false;
2912}
2913
Eric Laurent275e8e92014-11-30 15:14:47 -08002914// Register a list of custom mixes with their attributes and format.
2915// When a mix is registered, corresponding input and output profiles are
2916// added to the remote submix hw module. The profile contains only the
2917// parameters (sampling rate, format...) specified by the mix.
2918// The corresponding input remote submix device is also connected.
2919//
2920// When a remote submix device is connected, the address is checked to select the
2921// appropriate profile and the corresponding input or output stream is opened.
2922//
2923// When capture starts, getInputForAttr() will:
2924// - 1 look for a mix matching the address passed in attribtutes tags if any
2925// - 2 if none found, getDeviceForInputSource() will:
2926// - 2.1 look for a mix matching the attributes source
2927// - 2.2 if none found, default to device selection by policy rules
2928// At this time, the corresponding output remote submix device is also connected
2929// and active playback use cases can be transferred to this mix if needed when reconnecting
2930// after AudioTracks are invalidated
2931//
2932// When playback starts, getOutputForAttr() will:
2933// - 1 look for a mix matching the address passed in attribtutes tags if any
2934// - 2 if none found, look for a mix matching the attributes usage
2935// - 3 if none found, default to device and output selection by policy rules.
2936
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002937status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002938{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002939 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2940 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002941 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002942 sp<HwModule> rSubmixModule;
2943 // examine each mix's route type
2944 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002945 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002946 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2947 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2948 ALOGE("Unsupported Policy Mix %zu of %zu: "
2949 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2950 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002951 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002952 break;
2953 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002954 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2955 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002956 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002957 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2958 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002959 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002960 rSubmixModule = mHwModules.getModuleFromName(
2961 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2962 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002963 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002964 i);
2965 res = INVALID_OPERATION;
2966 break;
2967 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002968 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002969
Eric Laurent97ac8712018-07-27 18:59:02 -07002970 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002971 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002972 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002973 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002974 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2975 } else {
2976 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2977 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002978 }
François Gaffie036e1e92015-03-19 10:16:24 +01002979
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002980 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002981 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002982 res = INVALID_OPERATION;
2983 break;
2984 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002985 audio_config_t outputConfig = mix.mFormat;
2986 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07002987 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
2988 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002989 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2990 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07002991 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002992 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07002993 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002994 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002995
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002996 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002997 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2998 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2999 ALOGE("Failed to set remote submix device available, type %u, address %s",
3000 mix.mDeviceType, address.string());
3001 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003002 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003003 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3004 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003005 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003006 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003007 i, mixes.size(), type, address.string());
3008
3009 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3010 mix.mDeviceType, mix.mDeviceAddress,
3011 String8(), AUDIO_FORMAT_DEFAULT);
3012 if (device == nullptr) {
3013 res = INVALID_OPERATION;
3014 break;
3015 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003016
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003017 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003018 // First try to find an already opened output supporting the device
3019 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003020 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003021
Eric Laurentc529cf62020-04-17 18:19:10 -07003022 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003023 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003024 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3025 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003026 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003027 } else {
3028 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003029 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003030 }
3031 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003032 // If no output found, try to find a direct output profile supporting the device
3033 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3034 sp<HwModule> module = mHwModules[i];
3035 for (size_t j = 0;
3036 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3037 j++) {
3038 sp<IOProfile> profile = module->getOutputProfiles()[j];
3039 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3040 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3041 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3042 address.string());
3043 res = INVALID_OPERATION;
3044 } else {
3045 foundOutput = true;
3046 }
3047 }
3048 }
3049 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003050 if (res != NO_ERROR) {
3051 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003052 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003053 res = INVALID_OPERATION;
3054 break;
3055 } else if (!foundOutput) {
3056 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003057 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003058 res = INVALID_OPERATION;
3059 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003060 } else {
3061 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003062 }
Eric Laurentc722f302014-12-10 11:21:49 -08003063 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003064 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003065 if (res != NO_ERROR) {
3066 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003067 } else if (checkOutputs) {
3068 checkForDeviceAndOutputChanges();
3069 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003070 }
3071 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003072}
3073
3074status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3075{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003076 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003077 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003078 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003079 sp<HwModule> rSubmixModule;
3080 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003081 for (const auto& mix : mixes) {
3082 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003083
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003084 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003085 rSubmixModule = mHwModules.getModuleFromName(
3086 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3087 if (rSubmixModule == 0) {
3088 res = INVALID_OPERATION;
3089 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003090 }
3091 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003092
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003093 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003094
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003095 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003096 res = INVALID_OPERATION;
3097 continue;
3098 }
3099
Kevin Rocard04ed0462019-05-02 17:53:24 -07003100 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3101 if (getDeviceConnectionState(device, address.string()) ==
3102 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3103 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3104 address.string(), "remote-submix",
3105 AUDIO_FORMAT_DEFAULT);
3106 if (res != OK) {
3107 ALOGE("Error making RemoteSubmix device unavailable for mix "
3108 "with type %d, address %s", device, address.string());
3109 }
3110 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003111 }
jiabin5740f082019-08-19 15:08:30 -07003112 rSubmixModule->removeOutputProfile(address.c_str());
3113 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114
Kevin Rocard153f92d2018-12-18 18:33:28 -08003115 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003116 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 res = INVALID_OPERATION;
3118 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003119 } else {
3120 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003121 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003123 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003124 if (res == NO_ERROR && checkOutputs) {
3125 checkForDeviceAndOutputChanges();
3126 updateCallAndOutputRouting();
3127 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003129}
3130
Mikhail Naganov100f0122018-11-29 11:22:16 -08003131void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3132{
3133 size_t i = 0;
3134 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3135 for (const auto& fmt : mManualSurroundFormats) {
3136 if (i++ != 0) dst->append(", ");
3137 std::string sfmt;
3138 FormatConverter::toString(fmt, sfmt);
3139 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3140 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3141 }
3142}
3143
Eric Laurentc529cf62020-04-17 18:19:10 -07003144// Returns true if all devices types match the predicate and are supported by one HW module
3145bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003146 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003147 std::function<bool(audio_devices_t)> predicate,
3148 const char *context) {
3149 for (size_t i = 0; i < devices.size(); i++) {
3150 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003151 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003152 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003153 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003154 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003155 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003156 return false;
3157 }
3158 }
3159 return true;
3160}
3161
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003162status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003163 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003164 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003165 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3166 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003167 }
3168 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003169 if (res != NO_ERROR) {
3170 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3171 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003172 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003173
3174 checkForDeviceAndOutputChanges();
3175 updateCallAndOutputRouting();
3176
3177 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003178}
3179
3180status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3181 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003182 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3183 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003184 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003185 __FUNCTION__, uid);
3186 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003187 }
3188
Eric Laurentc529cf62020-04-17 18:19:10 -07003189 checkForDeviceAndOutputChanges();
3190 updateCallAndOutputRouting();
3191
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003192 return res;
3193}
3194
Eric Laurent2517af32020-11-25 15:31:27 +01003195
jiabin0a488932020-08-07 17:32:40 -07003196status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3197 device_role_t role,
3198 const AudioDeviceTypeAddrVector &devices) {
3199 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3200 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003201
Eric Laurentc529cf62020-04-17 18:19:10 -07003202 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003203 return BAD_VALUE;
3204 }
jiabin0a488932020-08-07 17:32:40 -07003205 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003206 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003207 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3208 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003209 return status;
3210 }
3211
3212 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003213
3214 bool forceVolumeReeval = false;
3215 // FIXME: workaround for truncated touch sounds
3216 // to be removed when the problem is handled by system UI
3217 uint32_t delayMs = 0;
3218 if (strategy == mCommunnicationStrategy) {
3219 forceVolumeReeval = true;
3220 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3221 updateInputRouting();
3222 }
3223 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003224
3225 return NO_ERROR;
3226}
3227
3228void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3229{
3230 uint32_t waitMs = 0;
3231 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3232 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3233 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003234 // Only apply special touch sound delay once
3235 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003236 }
3237 for (size_t i = 0; i < mOutputs.size(); i++) {
3238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3239 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3240 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3241 // As done in setDeviceConnectionState, we could also fix default device issue by
3242 // preventing the force re-routing in case of default dev that distinguishes on address.
3243 // Let's give back to engine full device choice decision however.
3244 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003245 // Only apply special touch sound delay once
3246 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003247 }
3248 if (forceVolumeReeval && !newDevices.isEmpty()) {
3249 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3250 }
3251 }
3252}
3253
Eric Laurent2517af32020-11-25 15:31:27 +01003254void AudioPolicyManager::updateInputRouting() {
3255 for (const auto& activeDesc : mInputs.getActiveInputs()) {
3256 auto newDevice = getNewInputDevice(activeDesc);
3257 // Force new input selection if the new device can not be reached via current input
3258 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3259 setInputDevice(activeDesc->mIoHandle, newDevice);
3260 } else {
3261 closeInput(activeDesc->mIoHandle);
3262 }
3263 }
3264}
3265
jiabin0a488932020-08-07 17:32:40 -07003266status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3267 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003268{
jiabin0a488932020-08-07 17:32:40 -07003269 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003270
jiabin0a488932020-08-07 17:32:40 -07003271 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003272 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003273 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3274 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003275 return status;
3276 }
3277
3278 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003279
3280 bool forceVolumeReeval = false;
3281 // FIXME: workaround for truncated touch sounds
3282 // to be removed when the problem is handled by system UI
3283 uint32_t delayMs = 0;
3284 if (strategy == mCommunnicationStrategy) {
3285 forceVolumeReeval = true;
3286 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3287 updateInputRouting();
3288 }
3289 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003290
3291 return NO_ERROR;
3292}
3293
jiabin0a488932020-08-07 17:32:40 -07003294status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3295 device_role_t role,
3296 AudioDeviceTypeAddrVector &devices) {
3297 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003298}
3299
Jiabin Huang3b98d322020-09-03 17:54:16 +00003300status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3301 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3302 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3303 dumpAudioDeviceTypeAddrVector(devices).c_str());
3304
Mikhail Naganov55773032020-10-01 15:08:13 -07003305 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003306 return BAD_VALUE;
3307 }
3308 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3309 ALOGW_IF(status != NO_ERROR,
3310 "Engine could not set preferred devices %s for audio source %d role %d",
3311 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3312
3313 return status;
3314}
3315
3316status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3317 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3318 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3319 dumpAudioDeviceTypeAddrVector(devices).c_str());
3320
Mikhail Naganov55773032020-10-01 15:08:13 -07003321 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003322 return BAD_VALUE;
3323 }
3324 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3325 ALOGW_IF(status != NO_ERROR,
3326 "Engine could not add preferred devices %s for audio source %d role %d",
3327 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3328
Eric Laurent2517af32020-11-25 15:31:27 +01003329 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003330 return status;
3331}
3332
3333status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3334 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3335{
3336 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3337 dumpAudioDeviceTypeAddrVector(devices).c_str());
3338
Mikhail Naganov55773032020-10-01 15:08:13 -07003339 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003340 return BAD_VALUE;
3341 }
3342
3343 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3344 audioSource, role, devices);
3345 ALOGW_IF(status != NO_ERROR,
3346 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3347
Eric Laurent2517af32020-11-25 15:31:27 +01003348 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003349 return status;
3350}
3351
3352status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3353 device_role_t role) {
3354 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3355
3356 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3357 ALOGW_IF(status != NO_ERROR,
3358 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3359
Eric Laurent2517af32020-11-25 15:31:27 +01003360 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003361 return status;
3362}
3363
3364status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3365 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3366 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3367}
3368
Oscar Azucena90e77632019-11-27 17:12:28 -08003369status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003370 const AudioDeviceTypeAddrVector& devices) {
3371 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003372 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3373 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003374 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003375 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3376 if (status != NO_ERROR) {
3377 ALOGE("%s() could not set device affinity for userId %d",
3378 __FUNCTION__, userId);
3379 return status;
3380 }
3381
3382 // reevaluate outputs for all devices
3383 checkForDeviceAndOutputChanges();
3384 updateCallAndOutputRouting();
3385
3386 return NO_ERROR;
3387}
3388
3389status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3390 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3391 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3392 if (status != NO_ERROR) {
3393 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3394 __FUNCTION__, userId);
3395 return status;
3396 }
3397
3398 // reevaluate outputs for all devices
3399 checkForDeviceAndOutputChanges();
3400 updateCallAndOutputRouting();
3401
3402 return NO_ERROR;
3403}
3404
Andy Hungc29d82b2018-10-05 12:23:17 -07003405void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003406{
Andy Hungc29d82b2018-10-05 12:23:17 -07003407 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3408 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003409 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003410 std::string stateLiteral;
3411 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003412 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003413 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3414 "communications", "media", "record", "dock", "system",
3415 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3416 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3417 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003418 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3419 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3420 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3421 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3422 dst->append(" (MANUAL: ");
3423 dumpManualSurroundFormats(dst);
3424 dst->append(")");
3425 }
3426 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003427 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003428 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3429 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003430 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003431 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003432
Andy Hungc29d82b2018-10-05 12:23:17 -07003433 mAvailableOutputDevices.dump(dst, String8("Available output"));
3434 mAvailableInputDevices.dump(dst, String8("Available input"));
3435 mHwModulesAll.dump(dst);
3436 mOutputs.dump(dst);
3437 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003438 mEffects.dump(dst);
3439 mAudioPatches.dump(dst);
3440 mPolicyMixes.dump(dst);
3441 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003442
Kevin Rocardb99cc752019-03-21 20:52:24 -07003443 dst->appendFormat(" AllowedCapturePolicies:\n");
3444 for (auto& policy : mAllowedCapturePolicies) {
3445 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3446 }
3447
François Gaffiec005e562018-11-06 15:04:49 +01003448 dst->appendFormat("\nPolicy Engine dump:\n");
3449 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003450}
3451
3452status_t AudioPolicyManager::dump(int fd)
3453{
3454 String8 result;
3455 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003456 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003457 return NO_ERROR;
3458}
3459
Kevin Rocardb99cc752019-03-21 20:52:24 -07003460status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3461{
3462 mAllowedCapturePolicies[uid] = capturePolicy;
3463 return NO_ERROR;
3464}
3465
Eric Laurente552edb2014-03-10 17:42:56 -07003466// This function checks for the parameters which can be offloaded.
3467// This can be enhanced depending on the capability of the DSP and policy
3468// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003469audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003470{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003471 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003472 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003473 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003474 offloadInfo.format,
3475 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3476 offloadInfo.has_video);
3477
Andy Hung2ddee192015-12-18 17:34:44 -08003478 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003479 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003480 }
3481
Eric Laurente552edb2014-03-10 17:42:56 -07003482 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003483 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003484 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3485 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003486 }
3487
3488 // Check if stream type is music, then only allow offload as of now.
3489 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3490 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003491 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3492 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003493 }
3494
3495 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003496 const bool allowOffloadWithVideo =
3497 property_get_bool("audio.offload.video", false /* default_value */);
3498 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003499 ALOGV("%s: has_video == true, returning false", __func__);
3500 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003501 }
3502
3503 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003504 const int min_duration_secs = property_get_int32(
3505 "audio.offload.min.duration.secs", -1 /* default_value */);
3506 if (min_duration_secs >= 0) {
3507 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003508 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3509 __func__, min_duration_secs);
3510 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003513 ALOGV("%s: Offload denied by duration < default min(=%u)",
3514 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3515 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003516 }
3517
3518 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3519 // creating an offloaded track and tearing it down immediately after start when audioflinger
3520 // detects there is an active non offloadable effect.
3521 // FIXME: We should check the audio session here but we do not have it in this context.
3522 // This may prevent offloading in rare situations where effects are left active by apps
3523 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003524 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003525 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003526 }
3527
3528 // See if there is a profile to support this.
3529 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003530 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003531 offloadInfo.sample_rate,
3532 offloadInfo.format,
3533 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003534 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3535 true /* directOnly */);
Eric Laurent90fe31c2020-11-26 20:06:35 +01003536 ALOGV("%s: profile %sfound", __func__, profile != 0 ? "" : "NOT ");
3537 if (profile == nullptr) {
3538 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3539 }
3540 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3541 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3542 }
3543 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003544}
3545
Michael Chana94fbb22018-04-24 14:31:19 +10003546bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3547 const audio_attributes_t& attributes) {
3548 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003549 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003550 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003551 config.sample_rate,
3552 config.format,
3553 config.channel_mask,
3554 output_flags,
3555 true /* directOnly */);
3556 ALOGV("%s() profile %sfound with name: %s, "
3557 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3558 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003559 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003560 config.sample_rate, config.format, config.channel_mask, output_flags);
3561 return (profile != 0);
3562}
3563
Eric Laurent6a94d692014-05-20 11:18:06 -07003564status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3565 audio_port_type_t type,
3566 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003567 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003568 unsigned int *generation)
3569{
jiabin19cdba52020-11-24 11:28:58 -08003570 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3571 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003572 return BAD_VALUE;
3573 }
3574 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003575 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003576 *num_ports = 0;
3577 }
3578
3579 size_t portsWritten = 0;
3580 size_t portsMax = *num_ports;
3581 *num_ports = 0;
3582 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003583 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3584 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003585 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003586 for (const auto& dev : mAvailableOutputDevices) {
3587 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003588 continue;
3589 }
3590 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003591 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003592 }
3593 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003594 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003595 }
3596 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003597 for (const auto& dev : mAvailableInputDevices) {
3598 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003599 continue;
3600 }
3601 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003602 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003603 }
3604 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003605 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003606 }
3607 }
3608 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3609 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3610 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3611 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3612 }
3613 *num_ports += mInputs.size();
3614 }
3615 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003616 size_t numOutputs = 0;
3617 for (size_t i = 0; i < mOutputs.size(); i++) {
3618 if (!mOutputs[i]->isDuplicated()) {
3619 numOutputs++;
3620 if (portsWritten < portsMax) {
3621 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3622 }
3623 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 }
Eric Laurent84c70242014-06-23 08:46:27 -07003625 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003626 }
3627 }
3628 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003629 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003630 return NO_ERROR;
3631}
3632
jiabin19cdba52020-11-24 11:28:58 -08003633status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003634{
Eric Laurent99fcae42018-05-17 16:59:18 -07003635 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3636 return BAD_VALUE;
3637 }
3638 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3639 if (dev != 0) {
3640 dev->toAudioPort(port);
3641 return NO_ERROR;
3642 }
3643 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3644 if (dev != 0) {
3645 dev->toAudioPort(port);
3646 return NO_ERROR;
3647 }
3648 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3649 if (out != 0) {
3650 out->toAudioPort(port);
3651 return NO_ERROR;
3652 }
3653 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3654 if (in != 0) {
3655 in->toAudioPort(port);
3656 return NO_ERROR;
3657 }
3658 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003659}
3660
François Gaffieafd4cea2019-11-18 15:50:22 +01003661status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3662 audio_patch_handle_t *handle,
3663 uid_t uid, uint32_t delayMs,
3664 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003665{
François Gaffieafd4cea2019-11-18 15:50:22 +01003666 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003667 if (handle == NULL || patch == NULL) {
3668 return BAD_VALUE;
3669 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003670 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003671
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003672 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003673 return BAD_VALUE;
3674 }
3675 // only one source per audio patch supported for now
3676 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003677 return INVALID_OPERATION;
3678 }
Eric Laurent874c42872014-08-08 15:13:39 -07003679
3680 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003681 return INVALID_OPERATION;
3682 }
Eric Laurent874c42872014-08-08 15:13:39 -07003683 for (size_t i = 0; i < patch->num_sinks; i++) {
3684 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3685 return INVALID_OPERATION;
3686 }
3687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003688
3689 sp<AudioPatch> patchDesc;
3690 ssize_t index = mAudioPatches.indexOfKey(*handle);
3691
François Gaffieafd4cea2019-11-18 15:50:22 +01003692 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3693 patch->sources[0].role,
3694 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003695#if LOG_NDEBUG == 0
3696 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003697 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3698 patch->sinks[i].role,
3699 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003700 }
3701#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003702
3703 if (index >= 0) {
3704 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003705 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3706 __func__, mUidCached, patchDesc->getUid(), uid);
3707 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003708 return INVALID_OPERATION;
3709 }
3710 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003711 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003712 }
3713
3714 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003715 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003716 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003717 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003718 return BAD_VALUE;
3719 }
Eric Laurent84c70242014-06-23 08:46:27 -07003720 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3721 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003722 if (patchDesc != 0) {
3723 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003724 ALOGV("%s source id differs for patch current id %d new id %d",
3725 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003726 return BAD_VALUE;
3727 }
3728 }
Eric Laurent874c42872014-08-08 15:13:39 -07003729 DeviceVector devices;
3730 for (size_t i = 0; i < patch->num_sinks; i++) {
3731 // Only support mix to devices connection
3732 // TODO add support for mix to mix connection
3733 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003734 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003735 return INVALID_OPERATION;
3736 }
3737 sp<DeviceDescriptor> devDesc =
3738 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3739 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003740 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003741 return BAD_VALUE;
3742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003743
François Gaffie11d30102018-11-02 16:09:09 +01003744 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003745 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003746 NULL, // updatedSamplingRate
3747 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003748 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003749 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003750 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003751 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003752 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003753 return INVALID_OPERATION;
3754 }
3755 devices.add(devDesc);
3756 }
3757 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003758 return INVALID_OPERATION;
3759 }
Eric Laurent874c42872014-08-08 15:13:39 -07003760
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003762 ALOGV("%s setting device %s on output %d",
3763 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003764 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 index = mAudioPatches.indexOfKey(*handle);
3766 if (index >= 0) {
3767 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003768 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003769 }
3770 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003771 patchDesc->setUid(uid);
3772 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003773 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003774 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003775 return INVALID_OPERATION;
3776 }
3777 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3778 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3779 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003780 // only one sink supported when connecting an input device to a mix
3781 if (patch->num_sinks > 1) {
3782 return INVALID_OPERATION;
3783 }
François Gaffie53615e22015-03-19 09:24:12 +01003784 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003785 if (inputDesc == NULL) {
3786 return BAD_VALUE;
3787 }
3788 if (patchDesc != 0) {
3789 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3790 return BAD_VALUE;
3791 }
3792 }
François Gaffie11d30102018-11-02 16:09:09 +01003793 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003794 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003795 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003796 return BAD_VALUE;
3797 }
3798
François Gaffie11d30102018-11-02 16:09:09 +01003799 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003800 patch->sinks[0].sample_rate,
3801 NULL, /*updatedSampleRate*/
3802 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003803 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003804 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003805 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003806 // FIXME for the parameter type,
3807 // and the NONE
3808 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003809 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003810 return INVALID_OPERATION;
3811 }
3812 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003813 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003814 device->toString().c_str(), inputDesc->mIoHandle);
3815 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003816 index = mAudioPatches.indexOfKey(*handle);
3817 if (index >= 0) {
3818 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003819 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 }
3821 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003822 patchDesc->setUid(uid);
3823 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003824 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003825 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 return INVALID_OPERATION;
3827 }
3828 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3829 // device to device connection
3830 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003831 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 return BAD_VALUE;
3833 }
3834 }
François Gaffie11d30102018-11-02 16:09:09 +01003835 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003837 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003838 return BAD_VALUE;
3839 }
Eric Laurent874c42872014-08-08 15:13:39 -07003840
Eric Laurent6a94d692014-05-20 11:18:06 -07003841 //update source and sink with our own data as the data passed in the patch may
3842 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003843 PatchBuilder patchBuilder;
3844 audio_port_config sourcePortConfig = {};
3845 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3846 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003847
Eric Laurent874c42872014-08-08 15:13:39 -07003848 for (size_t i = 0; i < patch->num_sinks; i++) {
3849 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003851 return INVALID_OPERATION;
3852 }
François Gaffie11d30102018-11-02 16:09:09 +01003853 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003854 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003855 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003856 return BAD_VALUE;
3857 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003858 audio_port_config sinkPortConfig = {};
3859 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3860 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003861
Eric Laurent3bcf8592015-04-03 12:13:24 -07003862 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003863 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003864 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003865 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003866 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3867 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003868 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3869 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003870 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3871 (sourceDesc != nullptr &&
3872 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003873 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003874 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003875 return INVALID_OPERATION;
3876 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003877 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3878 if (sourceDesc != nullptr) {
3879 // take care of dynamic routing for SwOutput selection,
3880 audio_attributes_t attributes = sourceDesc->attributes();
3881 audio_stream_type_t stream = sourceDesc->stream();
3882 audio_attributes_t resultAttr;
3883 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3884 config.sample_rate = sourceDesc->config().sample_rate;
3885 config.channel_mask = sourceDesc->config().channel_mask;
3886 config.format = sourceDesc->config().format;
3887 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3888 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3889 bool isRequestedDeviceForExclusiveUse = false;
François Gaffieafd4cea2019-11-18 15:50:22 +01003890 output_type_t outputType;
3891 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3892 &stream, sourceDesc->uid(), &config, &flags,
3893 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07003894 nullptr, &outputType);
François Gaffieafd4cea2019-11-18 15:50:22 +01003895 if (output == AUDIO_IO_HANDLE_NONE) {
3896 ALOGV("%s no output for device %s",
3897 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003898 return INVALID_OPERATION;
3899 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003900 } else {
3901 SortedVector<audio_io_handle_t> outputs =
3902 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3903 // if the sink device is reachable via an opened output stream, request to
3904 // go via this output stream by adding a second source to the patch
3905 // description
3906 output = selectOutput(outputs);
3907 }
3908 if (output != AUDIO_IO_HANDLE_NONE) {
3909 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3910 if (outputDesc->isDuplicated()) {
3911 ALOGV("%s output for device %s is duplicated",
3912 __FUNCTION__, sinkDevice->toString().c_str());
3913 return INVALID_OPERATION;
3914 }
3915 audio_port_config srcMixPortConfig = {};
3916 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3917 if (sourceDesc != nullptr) {
3918 sourceDesc->setSwOutput(outputDesc);
3919 }
3920 // for volume control, we may need a valid stream
3921 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3922 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3923 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003924 }
Eric Laurent83b88082014-06-20 18:31:16 -07003925 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 }
3927 // TODO: check from routing capabilities in config file and other conflicting patches
3928
François Gaffieafd4cea2019-11-18 15:50:22 +01003929 status_t status = installPatch(
3930 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003931 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003932 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003933 return INVALID_OPERATION;
3934 }
3935 } else {
3936 return BAD_VALUE;
3937 }
3938 } else {
3939 return BAD_VALUE;
3940 }
3941 return NO_ERROR;
3942}
3943
3944status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3945 uid_t uid)
3946{
3947 ALOGV("releaseAudioPatch() patch %d", handle);
3948
3949 ssize_t index = mAudioPatches.indexOfKey(handle);
3950
3951 if (index < 0) {
3952 return BAD_VALUE;
3953 }
3954 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003955 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3956 __func__, mUidCached, patchDesc->getUid(), uid);
3957 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003958 return INVALID_OPERATION;
3959 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003960 return releaseAudioPatchInternal(handle);
3961}
Eric Laurent6a94d692014-05-20 11:18:06 -07003962
François Gaffieafd4cea2019-11-18 15:50:22 +01003963status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3964 uint32_t delayMs)
3965{
3966 ALOGV("%s patch %d", __func__, handle);
3967 if (mAudioPatches.indexOfKey(handle) < 0) {
3968 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3969 return BAD_VALUE;
3970 }
3971 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01003973 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003975 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003977 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003978 return BAD_VALUE;
3979 }
3980
François Gaffie11d30102018-11-02 16:09:09 +01003981 setOutputDevices(outputDesc,
3982 getNewOutputDevices(outputDesc, true /*fromCache*/),
3983 true,
3984 0,
3985 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003986 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3987 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003988 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003990 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 return BAD_VALUE;
3992 }
3993 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003994 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 true,
3996 NULL);
3997 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003998 status_t status =
3999 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4000 ALOGV("%s patch panel returned %d patchHandle %d",
4001 __func__, status, patchDesc->getAfHandle());
4002 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004003 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004004 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004005 // SW Bridge
4006 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4007 sp<SwAudioOutputDescriptor> outputDesc =
4008 mOutputs.getOutputFromId(patch->sources[1].id);
4009 if (outputDesc == NULL) {
4010 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
4011 return BAD_VALUE;
4012 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004013 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4014 // force SwOutput patch removal as AF counter part patch has already gone.
4015 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4016 removeAudioPatch(outputDesc->getPatchHandle());
4017 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004018 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4019 setOutputDevices(outputDesc,
4020 getNewOutputDevices(outputDesc, true /*fromCache*/),
4021 true, /*force*/
4022 0,
4023 NULL);
4024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 } else {
4026 return BAD_VALUE;
4027 }
4028 } else {
4029 return BAD_VALUE;
4030 }
4031 return NO_ERROR;
4032}
4033
4034status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4035 struct audio_patch *patches,
4036 unsigned int *generation)
4037{
François Gaffie53615e22015-03-19 09:24:12 +01004038 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004039 return BAD_VALUE;
4040 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004041 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004042 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004043}
4044
Eric Laurente1715a42014-05-20 11:30:42 -07004045status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004046{
Eric Laurente1715a42014-05-20 11:30:42 -07004047 ALOGV("setAudioPortConfig()");
4048
4049 if (config == NULL) {
4050 return BAD_VALUE;
4051 }
4052 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4053 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004054 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4055 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004056 }
4057
Eric Laurenta121f902014-06-03 13:32:54 -07004058 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004059 if (config->type == AUDIO_PORT_TYPE_MIX) {
4060 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004061 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004062 if (outputDesc == NULL) {
4063 return BAD_VALUE;
4064 }
Eric Laurent84c70242014-06-23 08:46:27 -07004065 ALOG_ASSERT(!outputDesc->isDuplicated(),
4066 "setAudioPortConfig() called on duplicated output %d",
4067 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004068 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004069 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004070 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004071 if (inputDesc == NULL) {
4072 return BAD_VALUE;
4073 }
Eric Laurenta121f902014-06-03 13:32:54 -07004074 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004075 } else {
4076 return BAD_VALUE;
4077 }
4078 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4079 sp<DeviceDescriptor> deviceDesc;
4080 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4081 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4082 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4083 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4084 } else {
4085 return BAD_VALUE;
4086 }
4087 if (deviceDesc == NULL) {
4088 return BAD_VALUE;
4089 }
Eric Laurenta121f902014-06-03 13:32:54 -07004090 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004091 } else {
4092 return BAD_VALUE;
4093 }
4094
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004095 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004096 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4097 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004098 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004099 audioPortConfig->toAudioPortConfig(&newConfig, config);
4100 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004101 }
Eric Laurenta121f902014-06-03 13:32:54 -07004102 if (status != NO_ERROR) {
4103 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004104 }
Eric Laurente1715a42014-05-20 11:30:42 -07004105
4106 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004107}
4108
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004109void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4110{
Eric Laurentd60560a2015-04-10 11:31:20 -07004111 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004112 clearAudioPatches(uid);
4113 clearSessionRoutes(uid);
4114}
4115
Eric Laurent6a94d692014-05-20 11:18:06 -07004116void AudioPolicyManager::clearAudioPatches(uid_t uid)
4117{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004118 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004119 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004120 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004121 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004122 }
4123 }
4124}
4125
François Gaffiec005e562018-11-06 15:04:49 +01004126void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004127{
François Gaffiec005e562018-11-06 15:04:49 +01004128 // Take the first attributes following the product strategy as it is used to retrieve the routed
4129 // device. All attributes wihin a strategy follows the same "routing strategy"
4130 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4131 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004132 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004133 for (size_t j = 0; j < mOutputs.size(); j++) {
4134 if (mOutputs.keyAt(j) == ouptutToSkip) {
4135 continue;
4136 }
4137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004138 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004139 continue;
4140 }
4141 // If the default device for this strategy is on another output mix,
4142 // invalidate all tracks in this strategy to force re connection.
4143 // Otherwise select new device on the output mix.
4144 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004145 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4146 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004147 }
4148 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004149 setOutputDevices(
4150 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004151 }
4152 }
4153}
4154
4155void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4156{
4157 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004158 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004159 for (size_t i = 0; i < mOutputs.size(); i++) {
4160 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004161 for (const auto& client : outputDesc->getClientIterable()) {
4162 if (client->hasPreferredDevice() && client->uid() == uid) {
4163 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004164 auto clientStrategy = client->strategy();
4165 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4166 end(affectedStrategies)) {
4167 continue;
4168 }
4169 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004170 }
4171 }
4172 }
4173 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004174 for (const auto& strategy : affectedStrategies) {
4175 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004176 }
4177
4178 // remove input routes associated with this uid
4179 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004180 for (size_t i = 0; i < mInputs.size(); i++) {
4181 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004182 for (const auto& client : inputDesc->getClientIterable()) {
4183 if (client->hasPreferredDevice() && client->uid() == uid) {
4184 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4185 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004186 }
4187 }
4188 }
4189 // reroute inputs if necessary
4190 SortedVector<audio_io_handle_t> inputsToClose;
4191 for (size_t i = 0; i < mInputs.size(); i++) {
4192 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004193 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004194 inputsToClose.add(inputDesc->mIoHandle);
4195 }
4196 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004197 for (const auto& input : inputsToClose) {
4198 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004199 }
4200}
4201
Eric Laurentd60560a2015-04-10 11:31:20 -07004202void AudioPolicyManager::clearAudioSources(uid_t uid)
4203{
4204 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004205 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4206 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004207 stopAudioSource(mAudioSources.keyAt(i));
4208 }
4209 }
4210}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004211
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004212status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4213 audio_io_handle_t *ioHandle,
4214 audio_devices_t *device)
4215{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004216 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4217 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004218 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004219 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004220
François Gaffiedf372692015-03-19 10:43:27 +01004221 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004222}
4223
Eric Laurentd60560a2015-04-10 11:31:20 -07004224status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004225 const audio_attributes_t *attributes,
4226 audio_port_handle_t *portId,
4227 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004228{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004229 ALOGV("%s", __FUNCTION__);
4230 *portId = AUDIO_PORT_HANDLE_NONE;
4231
4232 if (source == NULL || attributes == NULL || portId == NULL) {
4233 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4234 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004235 return BAD_VALUE;
4236 }
4237
Eric Laurentd60560a2015-04-10 11:31:20 -07004238 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4239 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004240 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4241 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004242 return INVALID_OPERATION;
4243 }
4244
François Gaffie11d30102018-11-02 16:09:09 +01004245 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004246 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004247 String8(source->ext.device.address),
4248 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004249 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004250 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004251 return BAD_VALUE;
4252 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004253
jiabin4ef93452019-09-10 14:29:54 -07004254 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004255
François Gaffieaaac0fd2018-11-22 17:56:39 +01004256 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004257 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004258 mEngine->getStreamTypeForAttributes(*attributes),
4259 mEngine->getProductStrategyForAttributes(*attributes),
4260 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004261
4262 status_t status = connectAudioSource(sourceDesc);
4263 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004264 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004265 }
4266 return status;
4267}
4268
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004269status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004270{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004271 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004272
4273 // make sure we only have one patch per source.
4274 disconnectAudioSource(sourceDesc);
4275
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004276 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01004277 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07004278
François Gaffiec005e562018-11-06 15:04:49 +01004279 DeviceVector sinkDevices =
4280 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
4281 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004282 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
4283 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
4284 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07004285
François Gaffieafd4cea2019-11-18 15:50:22 +01004286 PatchBuilder patchBuilder;
4287 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4288 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4289 status_t status =
4290 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4291 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4292 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4293 return INVALID_OPERATION;
4294 }
4295 sourceDesc->setPatchHandle(handle);
4296 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4297 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4298 if (swOutput != 0) {
4299 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004300 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004301 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004302 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004303 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004304 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004305 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004306 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004308 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004309 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004310 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004311 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4312 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004313 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004314 if (delayMs != 0) {
4315 usleep(delayMs * 1000);
4316 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004317 } else {
4318 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4319 if (hwOutputDesc != 0) {
4320 // create Hwoutput and add to mHwOutputs
4321 } else {
4322 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4323 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004324 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004325 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004326
4327FailureSourceActive:
4328 swOutput->stop();
4329 releaseOutput(sourceDesc->portId());
4330FailureSourceAdded:
4331 sourceDesc->setSwOutput(nullptr);
4332FailureReleasePatch:
4333 releaseAudioPatchInternal(handle);
4334 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004335}
4336
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004337status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004338{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004339 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4340 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004341 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004342 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004343 return BAD_VALUE;
4344 }
4345 status_t status = disconnectAudioSource(sourceDesc);
4346
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004347 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004348 return status;
4349}
4350
Andy Hung2ddee192015-12-18 17:34:44 -08004351status_t AudioPolicyManager::setMasterMono(bool mono)
4352{
4353 if (mMasterMono == mono) {
4354 return NO_ERROR;
4355 }
4356 mMasterMono = mono;
4357 // if enabling mono we close all offloaded devices, which will invalidate the
4358 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4359 // for recreating the new AudioTrack as non-offloaded PCM.
4360 //
4361 // If disabling mono, we leave all tracks as is: we don't know which clients
4362 // and tracks are able to be recreated as offloaded. The next "song" should
4363 // play back offloaded.
4364 if (mMasterMono) {
4365 Vector<audio_io_handle_t> offloaded;
4366 for (size_t i = 0; i < mOutputs.size(); ++i) {
4367 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4368 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4369 offloaded.push(desc->mIoHandle);
4370 }
4371 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004372 for (const auto& handle : offloaded) {
4373 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004374 }
4375 }
4376 // update master mono for all remaining outputs
4377 for (size_t i = 0; i < mOutputs.size(); ++i) {
4378 updateMono(mOutputs.keyAt(i));
4379 }
4380 return NO_ERROR;
4381}
4382
4383status_t AudioPolicyManager::getMasterMono(bool *mono)
4384{
4385 *mono = mMasterMono;
4386 return NO_ERROR;
4387}
4388
Eric Laurentac9cef52017-06-09 15:46:26 -07004389float AudioPolicyManager::getStreamVolumeDB(
4390 audio_stream_type_t stream, int index, audio_devices_t device)
4391{
jiabin9a3361e2019-10-01 09:38:30 -07004392 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004393}
4394
jiabin81772902018-04-02 17:52:27 -07004395status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4396 audio_format_t *surroundFormats,
4397 bool *surroundFormatsEnabled,
4398 bool reported)
4399{
4400 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4401 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4402 return BAD_VALUE;
4403 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004404 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4405 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004406
4407 size_t formatsWritten = 0;
4408 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004409 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004410 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004411 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004412 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004413 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4414 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
Kriti Dangef6be8f2020-11-05 11:58:19 +01004415 audio_devices_t deviceType = device->type();
4416 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4417 // returns formats reported by HDMI devices.
4418 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4419 continue;
4420 }
4421 // Formats reported by sink devices
4422 std::unordered_set<audio_format_t> formatset;
4423 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4424 formatset.insert(it->second.begin(), it->second.end());
4425 }
4426
4427 // Formats hard-coded in the in policy configuration file (if any).
4428 FormatVector encodedFormats = device->encodedFormats();
4429 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4430 // Filter the formats which are supported by the vendor hardware.
4431 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4432 if (mConfig.getSurroundFormats().count(*it) != 0) {
4433 formats.insert(*it);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004434 } else {
4435 for (const auto& pair : mConfig.getSurroundFormats()) {
Kriti Dangef6be8f2020-11-05 11:58:19 +01004436 if (pair.second.count(*it) != 0) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004437 formats.insert(pair.first);
4438 break;
4439 }
4440 }
4441 }
4442 }
jiabin81772902018-04-02 17:52:27 -07004443 }
4444 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004445 for (const auto& pair : mConfig.getSurroundFormats()) {
4446 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004447 }
4448 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004449 *numSurroundFormats = formats.size();
4450 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4451 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004452 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004453 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004454 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004455 bool formatEnabled = true;
4456 switch (forceUse) {
4457 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4458 formatEnabled = mManualSurroundFormats.count(format) != 0;
4459 break;
4460 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4461 formatEnabled = false;
4462 break;
4463 default: // AUTO or ALWAYS => true
4464 break;
jiabin81772902018-04-02 17:52:27 -07004465 }
4466 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4467 }
jiabin81772902018-04-02 17:52:27 -07004468 }
4469 return NO_ERROR;
4470}
4471
4472status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4473{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004474 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004475 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4476 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004477 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004478 return BAD_VALUE;
4479 }
4480
Mikhail Naganov100f0122018-11-29 11:22:16 -08004481 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4482 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004483 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004484 return INVALID_OPERATION;
4485 }
4486
Mikhail Naganov100f0122018-11-29 11:22:16 -08004487 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004488 return NO_ERROR;
4489 }
4490
Mikhail Naganov100f0122018-11-29 11:22:16 -08004491 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004492 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004493 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004494 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004495 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004496 }
4497 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004498 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004499 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004500 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004501 }
4502 }
4503
4504 sp<SwAudioOutputDescriptor> outputDesc;
4505 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004506 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4507 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004508 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4509 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004510 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004511 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004512 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4513 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4514 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004515 name.c_str(),
4516 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004517 if (status != NO_ERROR) {
4518 continue;
4519 }
4520 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4522 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004523 name.c_str(),
4524 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004525 profileUpdated |= (status == NO_ERROR);
4526 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004527 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004528 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004529 AUDIO_DEVICE_IN_HDMI);
4530 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4531 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004532 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004533 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004534 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4535 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4536 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004537 name.c_str(),
4538 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004539 if (status != NO_ERROR) {
4540 continue;
4541 }
4542 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4543 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4544 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004545 name.c_str(),
4546 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004547 profileUpdated |= (status == NO_ERROR);
4548 }
4549
jiabin81772902018-04-02 17:52:27 -07004550 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004551 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004552 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004553 }
4554
4555 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4556}
4557
Eric Laurent5ada82e2019-08-29 17:53:54 -07004558void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004559{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004560 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004561 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004562 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004563 }
4564}
4565
jiabin6012f912018-11-02 17:06:30 -07004566bool AudioPolicyManager::isHapticPlaybackSupported()
4567{
4568 for (const auto& hwModule : mHwModules) {
4569 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4570 for (const auto &outProfile : outputProfiles) {
4571 struct audio_port audioPort;
4572 outProfile->toAudioPort(&audioPort);
4573 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4574 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4575 return true;
4576 }
4577 }
4578 }
4579 }
4580 return false;
4581}
4582
Eric Laurent8340e672019-11-06 11:01:08 -08004583bool AudioPolicyManager::isCallScreenModeSupported()
4584{
4585 return getConfig().isCallScreenModeSupported();
4586}
4587
4588
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004589status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004590{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004591 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffieafd4cea2019-11-18 15:50:22 +01004592 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4593 if (swOutput != 0) {
4594 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004595 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004596 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004597 }
jiabinbce0c1d2020-10-05 11:20:18 -07004598 if (releaseOutput(sourceDesc->portId())) {
4599 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4600 // no need to release audio patch here but just return NO_ERROR.
4601 return NO_ERROR;
4602 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004603 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004604 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004605 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004606 // close Hwoutput and remove from mHwOutputs
4607 } else {
4608 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4609 }
4610 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004612}
4613
François Gaffiec005e562018-11-06 15:04:49 +01004614sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4615 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004616{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004617 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004618 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004619 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004620 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004621 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4622 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004623 source = sourceDesc;
4624 break;
4625 }
4626 }
4627 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004628}
4629
Eric Laurente552edb2014-03-10 17:42:56 -07004630// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004631// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004632// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004633uint32_t AudioPolicyManager::nextAudioPortGeneration()
4634{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004635 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004636}
4637
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004638static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004639 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4640 !audioPolicyXmlConfigFile.empty()) {
4641 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4642 if (ret == NO_ERROR) {
4643 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004644 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004645 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004646 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004647 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004648}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004649
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004650AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4651 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004652 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004653 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004654 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004655 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004656 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004657 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004658 mAudioPortGeneration(1),
4659 mBeaconMuteRefCount(0),
4660 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004661 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004662 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004663 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004664 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004665{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004666}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004667
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004668AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4669 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4670{
4671 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004672}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004673
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004674void AudioPolicyManager::loadConfig() {
4675 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004676 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004677 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004678 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004679}
4680
4681status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004682 {
4683 auto engLib = EngineLibrary::load(
4684 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4685 if (!engLib) {
4686 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4687 return NO_INIT;
4688 }
4689 mEngine = engLib->createEngine();
4690 if (mEngine == nullptr) {
4691 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4692 return NO_INIT;
4693 }
François Gaffie2110e042015-03-24 08:41:51 +01004694 }
4695 mEngine->setObserver(this);
4696 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004697 if (status != NO_ERROR) {
4698 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4699 return status;
4700 }
François Gaffie2110e042015-03-24 08:41:51 +01004701
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004702 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004703 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004704 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004705
Eric Laurent3a4311c2014-03-17 12:00:47 -07004706 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004707 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4708 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4709 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004710 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004711 }
jiabin9ff780e2018-03-19 18:19:52 -07004712 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004713 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004714 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004715 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004716 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004717 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004718 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004719 }
4720 }
4721 }
Eric Laurente552edb2014-03-10 17:42:56 -07004722
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004723 if (mPrimaryOutput == 0) {
4724 ALOGE("Failed to open primary output");
4725 status = NO_INIT;
4726 }
Eric Laurente552edb2014-03-10 17:42:56 -07004727
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004728 // Silence ALOGV statements
4729 property_set("log.tag." LOG_TAG, "D");
4730
Eric Laurent2517af32020-11-25 15:31:27 +01004731 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4732 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4733
Eric Laurente552edb2014-03-10 17:42:56 -07004734 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004735 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004736}
4737
Eric Laurente0720872014-03-11 09:30:41 -07004738AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004739{
Eric Laurente552edb2014-03-10 17:42:56 -07004740 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004741 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004742 }
4743 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004744 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004745 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 mAvailableOutputDevices.clear();
4747 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004748 mOutputs.clear();
4749 mInputs.clear();
4750 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004751 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004752 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004753}
4754
Eric Laurente0720872014-03-11 09:30:41 -07004755status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004756{
Eric Laurent87ffa392015-05-22 10:32:38 -07004757 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004758}
4759
Eric Laurente552edb2014-03-10 17:42:56 -07004760// ---
4761
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004762void AudioPolicyManager::onNewAudioModulesAvailable()
4763{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004764 DeviceVector newDevices;
4765 onNewAudioModulesAvailableInt(&newDevices);
4766 if (!newDevices.empty()) {
4767 nextAudioPortGeneration();
4768 mpClientInterface->onAudioPortListUpdate();
4769 }
4770}
4771
4772void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4773{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004774 for (const auto& hwModule : mHwModulesAll) {
4775 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4776 continue;
4777 }
4778 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4779 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4780 ALOGW("could not open HW module %s", hwModule->getName());
4781 continue;
4782 }
4783 mHwModules.push_back(hwModule);
4784 // open all output streams needed to access attached devices
4785 // except for direct output streams that are only opened when they are actually
4786 // required by an app.
4787 // This also validates mAvailableOutputDevices list
4788 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4789 if (!outProfile->canOpenNewIo()) {
4790 ALOGE("Invalid Output profile max open count %u for profile %s",
4791 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4792 continue;
4793 }
4794 if (!outProfile->hasSupportedDevices()) {
4795 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4796 continue;
4797 }
4798 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4799 mTtsOutputAvailable = true;
4800 }
4801
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004802 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4803 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4804 sp<DeviceDescriptor> supportedDevice = 0;
4805 if (supportedDevices.contains(mDefaultOutputDevice)) {
4806 supportedDevice = mDefaultOutputDevice;
4807 } else {
4808 // choose first device present in profile's SupportedDevices also part of
4809 // mAvailableOutputDevices.
4810 if (availProfileDevices.isEmpty()) {
4811 continue;
4812 }
4813 supportedDevice = availProfileDevices.itemAt(0);
4814 }
4815 if (!mOutputDevicesAll.contains(supportedDevice)) {
4816 continue;
4817 }
4818 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4819 mpClientInterface);
4820 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4821 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4822 AUDIO_STREAM_DEFAULT,
4823 AUDIO_OUTPUT_FLAG_NONE, &output);
4824 if (status != NO_ERROR) {
4825 ALOGW("Cannot open output stream for devices %s on hw module %s",
4826 supportedDevice->toString().c_str(), hwModule->getName());
4827 continue;
4828 }
4829 for (const auto &device : availProfileDevices) {
4830 // give a valid ID to an attached device once confirmed it is reachable
4831 if (!device->isAttached()) {
4832 device->attach(hwModule);
4833 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004834 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004835 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004836 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4837 }
4838 }
4839 if (mPrimaryOutput == 0 &&
4840 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4841 mPrimaryOutput = outputDesc;
4842 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004843 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4844 outputDesc->close();
4845 } else {
4846 addOutput(output, outputDesc);
4847 setOutputDevices(outputDesc,
4848 DeviceVector(supportedDevice),
4849 true,
4850 0,
4851 NULL);
4852 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004853 }
4854 // open input streams needed to access attached devices to validate
4855 // mAvailableInputDevices list
4856 for (const auto& inProfile : hwModule->getInputProfiles()) {
4857 if (!inProfile->canOpenNewIo()) {
4858 ALOGE("Invalid Input profile max open count %u for profile %s",
4859 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4860 continue;
4861 }
4862 if (!inProfile->hasSupportedDevices()) {
4863 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4864 continue;
4865 }
4866 // chose first device present in profile's SupportedDevices also part of
4867 // available input devices
4868 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4869 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4870 if (availProfileDevices.isEmpty()) {
4871 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4872 continue;
4873 }
4874 sp<AudioInputDescriptor> inputDesc =
4875 new AudioInputDescriptor(inProfile, mpClientInterface);
4876
4877 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4878 status_t status = inputDesc->open(nullptr,
4879 availProfileDevices.itemAt(0),
4880 AUDIO_SOURCE_MIC,
4881 AUDIO_INPUT_FLAG_NONE,
4882 &input);
4883 if (status != NO_ERROR) {
4884 ALOGW("Cannot open input stream for device %s on hw module %s",
4885 availProfileDevices.toString().c_str(),
4886 hwModule->getName());
4887 continue;
4888 }
4889 for (const auto &device : availProfileDevices) {
4890 // give a valid ID to an attached device once confirmed it is reachable
4891 if (!device->isAttached()) {
4892 device->attach(hwModule);
4893 device->importAudioPortAndPickAudioProfile(inProfile, true);
4894 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004895 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004896 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4897 }
4898 }
4899 inputDesc->close();
4900 }
4901 }
4902}
4903
Eric Laurent98e38192018-02-15 18:31:53 -08004904void AudioPolicyManager::addOutput(audio_io_handle_t output,
4905 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004906{
Eric Laurent1c333e22014-05-20 10:48:17 -07004907 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004908 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004909 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004910 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004912}
4913
François Gaffie53615e22015-03-19 09:24:12 +01004914void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4915{
4916 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004917 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004918}
4919
Eric Laurent98e38192018-02-15 18:31:53 -08004920void AudioPolicyManager::addInput(audio_io_handle_t input,
4921 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004922{
Eric Laurent1c333e22014-05-20 10:48:17 -07004923 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004925}
Eric Laurente552edb2014-03-10 17:42:56 -07004926
François Gaffie11d30102018-11-02 16:09:09 +01004927status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004928 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004929 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004930{
François Gaffie11d30102018-11-02 16:09:09 +01004931 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07004932 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004933 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004934
François Gaffie11d30102018-11-02 16:09:09 +01004935 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004936 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004937 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004938 }
Eric Laurente552edb2014-03-10 17:42:56 -07004939
Eric Laurent3b73df72014-03-11 09:06:29 -07004940 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07004941 // first call getAudioPort to get the supported attributes from the HAL
4942 struct audio_port_v7 port = {};
4943 device->toAudioPort(&port);
4944 status_t status = mpClientInterface->getAudioPort(&port);
4945 if (status == NO_ERROR) {
4946 device->importAudioPort(port);
4947 }
4948
4949 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07004950 for (size_t i = 0; i < mOutputs.size(); i++) {
4951 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004952 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07004953 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004954 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4955 mOutputs.keyAt(i), device->toString().c_str());
4956 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004957 }
4958 }
4959 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004960 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004961 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004962 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4963 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004964 if (profile->supportsDevice(device)) {
4965 profiles.add(profile);
4966 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4967 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004968 }
4969 }
4970 }
4971
Eric Laurent7b279bb2015-12-14 10:18:23 -08004972 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004973
Eric Laurente552edb2014-03-10 17:42:56 -07004974 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004975 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004976 return BAD_VALUE;
4977 }
4978
4979 // open outputs for matching profiles if needed. Direct outputs are also opened to
4980 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4981 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004982 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004983
4984 // nothing to do if one output is already opened for this profile
4985 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004986 for (j = 0; j < outputs.size(); j++) {
4987 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004988 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004989 // matching profile: save the sample rates, format and channel masks supported
4990 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004991 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07004992 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004993 }
Eric Laurente552edb2014-03-10 17:42:56 -07004994 break;
4995 }
4996 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004997 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004998 continue;
4999 }
5000
Eric Laurent3974e3b2017-12-07 17:58:43 -08005001 if (!profile->canOpenNewIo()) {
5002 ALOGW("Max Output number %u already opened for this profile %s",
5003 profile->maxOpenCount, profile->getTagName().c_str());
5004 continue;
5005 }
5006
Eric Laurent83efe1c2017-07-09 16:51:08 -07005007 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005008 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005009 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5010 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005011 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005012 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005013 profiles.removeAt(profile_index);
5014 profile_index--;
5015 } else {
5016 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005017 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005018 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005019 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5020 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005021 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005022 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005023
François Gaffie11d30102018-11-02 16:09:09 +01005024 if (device_distinguishes_on_address(deviceType)) {
5025 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5026 device->toString().c_str());
5027 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5028 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005029 }
Eric Laurente552edb2014-03-10 17:42:56 -07005030 ALOGV("checkOutputsForDevice(): adding output %d", output);
5031 }
5032 }
5033
5034 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005035 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005036 return BAD_VALUE;
5037 }
Eric Laurentd4692962014-05-05 18:13:44 -07005038 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005039 // check if one opened output is not needed any more after disconnecting one device
5040 for (size_t i = 0; i < mOutputs.size(); i++) {
5041 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005042 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005043 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005044 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005045 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005046 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005047 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005048 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5049 mOutputs.keyAt(i));
5050 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005051 }
Eric Laurente552edb2014-03-10 17:42:56 -07005052 }
5053 }
Eric Laurentd4692962014-05-05 18:13:44 -07005054 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005055 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005056 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5057 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005058 if (!profile->supportsDevice(device)) {
5059 continue;
5060 }
5061 ALOGV("checkOutputsForDevice(): "
5062 "clearing direct output profile %zu on module %s",
5063 j, hwModule->getName());
5064 profile->clearAudioProfiles();
5065 if (!profile->hasDynamicAudioProfile()) {
5066 continue;
5067 }
5068 // When a device is disconnected, if there is an IOProfile that contains dynamic
5069 // profiles and supports the disconnected device, call getAudioPort to repopulate
5070 // the capabilities of the devices that is supported by the IOProfile.
5071 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5072 if (supportedDevice == device ||
5073 !mAvailableOutputDevices.contains(supportedDevice)) {
5074 continue;
5075 }
5076 struct audio_port_v7 port;
5077 supportedDevice->toAudioPort(&port);
5078 status_t status = mpClientInterface->getAudioPort(&port);
5079 if (status == NO_ERROR) {
5080 supportedDevice->importAudioPort(port);
5081 }
Eric Laurente552edb2014-03-10 17:42:56 -07005082 }
5083 }
5084 }
5085 }
5086 return NO_ERROR;
5087}
5088
François Gaffie11d30102018-11-02 16:09:09 +01005089status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005090 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005091{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005092 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005093
François Gaffie11d30102018-11-02 16:09:09 +01005094 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005095 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005096 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005097 }
5098
Eric Laurentd4692962014-05-05 18:13:44 -07005099 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005100 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005101 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005102 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005103 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005104 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005105 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005106 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005107
François Gaffie11d30102018-11-02 16:09:09 +01005108 if (profile->supportsDevice(device)) {
5109 profiles.add(profile);
5110 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5111 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005112 }
5113 }
5114 }
5115
Eric Laurent0dd51852019-04-19 18:18:58 -07005116 if (profiles.isEmpty()) {
5117 ALOGW("%s: No input profile available for device %s",
5118 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005119 return BAD_VALUE;
5120 }
5121
5122 // open inputs for matching profiles if needed. Direct inputs are also opened to
5123 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5124 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5125
Eric Laurent1c333e22014-05-20 10:48:17 -07005126 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005127
Eric Laurentd4692962014-05-05 18:13:44 -07005128 // nothing to do if one input is already opened for this profile
5129 size_t input_index;
5130 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5131 desc = mInputs.valueAt(input_index);
5132 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005133 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005134 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005135 }
Eric Laurentd4692962014-05-05 18:13:44 -07005136 break;
5137 }
5138 }
5139 if (input_index != mInputs.size()) {
5140 continue;
5141 }
5142
Eric Laurent3974e3b2017-12-07 17:58:43 -08005143 if (!profile->canOpenNewIo()) {
5144 ALOGW("Max Input number %u already opened for this profile %s",
5145 profile->maxOpenCount, profile->getTagName().c_str());
5146 continue;
5147 }
5148
Eric Laurentfe231122017-11-17 17:48:06 -08005149 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005150 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005151 status_t status = desc->open(nullptr,
5152 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005153 AUDIO_SOURCE_MIC,
5154 AUDIO_INPUT_FLAG_NONE,
5155 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005156
Eric Laurentcf2c0212014-07-25 16:20:43 -07005157 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005158 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005159 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005160 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005161 mpClientInterface->setParameters(input, String8(param));
5162 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005163 }
François Gaffie11d30102018-11-02 16:09:09 +01005164 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005165 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005166 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005167 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005168 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005169 }
5170
Eric Laurent0dd51852019-04-19 18:18:58 -07005171 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005172 addInput(input, desc);
5173 }
5174 } // endif input != 0
5175
Eric Laurentcf2c0212014-07-25 16:20:43 -07005176 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005177 ALOGW("%s could not open input for device %s", __func__,
5178 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005179 profiles.removeAt(profile_index);
5180 profile_index--;
5181 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005182 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005183 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005184 }
Eric Laurentd4692962014-05-05 18:13:44 -07005185 ALOGV("checkInputsForDevice(): adding input %d", input);
5186 }
5187 } // end scan profiles
5188
5189 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005190 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005191 return BAD_VALUE;
5192 }
5193 } else {
5194 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005195 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005196 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005197 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005198 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005199 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005200 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005201 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005202 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5203 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005204 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005205 }
5206 }
5207 }
5208 } // end disconnect
5209
5210 return NO_ERROR;
5211}
5212
5213
Eric Laurente0720872014-03-11 09:30:41 -07005214void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005215{
5216 ALOGV("closeOutput(%d)", output);
5217
François Gaffie1c878552018-11-22 16:53:21 +01005218 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5219 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005220 ALOGW("closeOutput() unknown output %d", output);
5221 return;
5222 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005223 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005224 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005225
Eric Laurente552edb2014-03-10 17:42:56 -07005226 // look for duplicated outputs connected to the output being removed.
5227 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005228 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5229 if (dupOutput->isDuplicated() &&
5230 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5231 sp<SwAudioOutputDescriptor> remainingOutput =
5232 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005233 // As all active tracks on duplicated output will be deleted,
5234 // and as they were also referenced on the other output, the reference
5235 // count for their stream type must be adjusted accordingly on
5236 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005237 const bool wasActive = remainingOutput->isActive();
5238 // Note: no-op on the closing output where all clients has already been set inactive
5239 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005240 // stop() will be a no op if the output is still active but is needed in case all
5241 // active streams refcounts where cleared above
5242 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005243 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005244 }
Eric Laurente552edb2014-03-10 17:42:56 -07005245 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5246 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5247
5248 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005249 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005250 }
5251 }
5252
Eric Laurent05b90f82014-08-27 15:32:29 -07005253 nextAudioPortGeneration();
5254
François Gaffie1c878552018-11-22 16:53:21 +01005255 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005256 if (index >= 0) {
5257 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5259 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005260 mAudioPatches.removeItemsAt(index);
5261 mpClientInterface->onAudioPatchListUpdate();
5262 }
5263
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005264 if (closingOutputWasActive) {
5265 closingOutput->stop();
5266 }
François Gaffie1c878552018-11-22 16:53:21 +01005267 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005268
François Gaffie53615e22015-03-19 09:24:12 +01005269 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005270 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005271
5272 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5273 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005274 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005275 bool directOutputOpen = false;
5276 for (size_t i = 0; i < mOutputs.size(); i++) {
5277 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5278 directOutputOpen = true;
5279 break;
5280 }
5281 }
5282 if (!directOutputOpen) {
5283 ALOGV("no direct outputs open, reset MSD patch");
5284 setMsdPatch();
5285 }
5286 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005287}
5288
5289void AudioPolicyManager::closeInput(audio_io_handle_t input)
5290{
5291 ALOGV("closeInput(%d)", input);
5292
5293 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5294 if (inputDesc == NULL) {
5295 ALOGW("closeInput() unknown input %d", input);
5296 return;
5297 }
5298
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005300
François Gaffie11d30102018-11-02 16:09:09 +01005301 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005302 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005303 if (index >= 0) {
5304 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005305 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5306 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005307 mAudioPatches.removeItemsAt(index);
5308 mpClientInterface->onAudioPatchListUpdate();
5309 }
5310
Eric Laurentfe231122017-11-17 17:48:06 -08005311 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005312 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005313
François Gaffie11d30102018-11-02 16:09:09 +01005314 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5315 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005316 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005317 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005318 }
Eric Laurente552edb2014-03-10 17:42:56 -07005319}
5320
François Gaffie11d30102018-11-02 16:09:09 +01005321SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5322 const DeviceVector &devices,
5323 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005324{
5325 SortedVector<audio_io_handle_t> outputs;
5326
François Gaffie11d30102018-11-02 16:09:09 +01005327 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005328 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005329 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005330 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005331 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005332 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005333 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005334 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005335 outputs.add(openOutputs.keyAt(i));
5336 }
5337 }
5338 return outputs;
5339}
5340
Mikhail Naganov37977152018-07-11 15:54:44 -07005341void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5342{
5343 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5344 // output is suspended before any tracks are moved to it
5345 checkA2dpSuspend();
5346 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005347 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005348 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005349 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005350 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005351 setMsdPatch();
5352 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005353}
5354
François Gaffiec005e562018-11-06 15:04:49 +01005355bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5356 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005357{
François Gaffiec005e562018-11-06 15:04:49 +01005358 return mEngine->getProductStrategyForAttributes(lAttr) ==
5359 mEngine->getProductStrategyForAttributes(rAttr);
5360}
5361
5362void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5363{
5364 auto psId = mEngine->getProductStrategyForAttributes(attr);
5365
5366 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5367 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005368
François Gaffie11d30102018-11-02 16:09:09 +01005369 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5370 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005371
Eric Laurentc209fe42020-06-05 18:11:23 -07005372 uint32_t maxLatency = 0;
5373 bool invalidate = false;
5374 // take into account dynamic audio policies related changes: if a client is now associated
5375 // to a different policy mix than at creation time, invalidate corresponding stream
5376 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5377 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5378 if (desc->isDuplicated()) {
5379 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005380 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005381 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5382 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5383 continue;
5384 }
5385 sp<AudioPolicyMix> primaryMix;
5386 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5387 client->flags(), primaryMix, nullptr);
5388 if (status != OK) {
5389 continue;
5390 }
yucliuf4de36d2020-09-14 14:57:56 -07005391 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005392 invalidate = true;
5393 if (desc->isStrategyActive(psId)) {
5394 maxLatency = desc->latency();
5395 }
5396 break;
5397 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005398 }
5399 }
5400
Eric Laurentc209fe42020-06-05 18:11:23 -07005401 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005402 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5403 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005404 for (audio_io_handle_t srcOut : srcOutputs) {
5405 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005406 if (desc == nullptr) continue;
5407
5408 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005409 maxLatency = desc->latency();
5410 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005411
5412 if (invalidate) continue;
5413
5414 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005415 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005416 // a client on a non direct outputs has necessarily a linear PCM format
5417 // so we can call selectOutput() safely
5418 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5419 client->flags(),
5420 client->config().format,
5421 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005422 client->config().sample_rate,
5423 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005424 if (newOutput != srcOut) {
5425 invalidate = true;
5426 break;
5427 }
5428 } else {
5429 sp<IOProfile> profile = getProfileForOutput(newDevices,
5430 client->config().sample_rate,
5431 client->config().format,
5432 client->config().channel_mask,
5433 client->flags(),
5434 true /* directOnly */);
5435 if (profile != desc->mProfile) {
5436 invalidate = true;
5437 break;
5438 }
5439 }
5440 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005441 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005442
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005443 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005444 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005445 std::to_string(srcOutputs[0]).c_str(),
5446 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005447 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005448 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005449 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005450 if (desc == nullptr) continue;
5451
5452 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005453 setStrategyMute(psId, true, desc);
5454 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005455 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005456 }
François Gaffiec005e562018-11-06 15:04:49 +01005457 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005458 if (source != 0){
5459 connectAudioSource(source);
5460 }
Eric Laurente552edb2014-03-10 17:42:56 -07005461 }
5462
François Gaffiec005e562018-11-06 15:04:49 +01005463 // Move effects associated to this stream from previous output to new output
5464 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005465 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005466 }
François Gaffiec005e562018-11-06 15:04:49 +01005467 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005468 if (invalidate) {
5469 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5470 mpClientInterface->invalidateStream(stream);
5471 }
Eric Laurente552edb2014-03-10 17:42:56 -07005472 }
5473 }
5474}
5475
Eric Laurente0720872014-03-11 09:30:41 -07005476void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005477{
François Gaffiec005e562018-11-06 15:04:49 +01005478 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5479 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5480 checkOutputForAttributes(attributes);
5481 }
Eric Laurente552edb2014-03-10 17:42:56 -07005482}
5483
Kevin Rocard153f92d2018-12-18 18:33:28 -08005484void AudioPolicyManager::checkSecondaryOutputs() {
5485 std::set<audio_stream_type_t> streamsToInvalidate;
5486 for (size_t i = 0; i < mOutputs.size(); i++) {
5487 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5488 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005489 sp<AudioPolicyMix> primaryMix;
5490 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005491 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005492 client->flags(), primaryMix, &secondaryMixes);
5493 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5494 for (auto &secondaryMix : secondaryMixes) {
5495 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5496 if (outputDesc != nullptr &&
5497 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5498 secondaryDescs.push_back(outputDesc);
5499 }
5500 }
5501
Kevin Rocard94114a22019-04-01 19:38:23 -07005502 if (status != OK ||
5503 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005504 client->getSecondaryOutputs().end(),
5505 secondaryDescs.begin(), secondaryDescs.end())) {
5506 streamsToInvalidate.insert(client->stream());
5507 }
5508 }
5509 }
5510 for (audio_stream_type_t stream : streamsToInvalidate) {
5511 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5512 mpClientInterface->invalidateStream(stream);
5513 }
5514}
5515
Eric Laurent2517af32020-11-25 15:31:27 +01005516bool AudioPolicyManager::isScoRequestedForComm() const {
5517 AudioDeviceTypeAddrVector devices;
5518 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5519 for (const auto &device : devices) {
5520 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5521 return true;
5522 }
5523 }
5524 return false;
5525}
5526
Eric Laurente0720872014-03-11 09:30:41 -07005527void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005528{
François Gaffie53615e22015-03-19 09:24:12 +01005529 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005530 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005531 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005532 return;
5533 }
5534
Eric Laurent3a4311c2014-03-17 12:00:47 -07005535 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005536 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5537 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005538 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005539
5540 // if suspended, restore A2DP output if:
5541 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005542 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005543 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005544 //
Eric Laurentf732e072016-08-03 19:30:28 -07005545 // if not suspended, suspend A2DP output if:
5546 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005547 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005548 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005549 //
5550 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005551 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005552 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005553 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005554 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005555
5556 mpClientInterface->restoreOutput(a2dpOutput);
5557 mA2dpSuspended = false;
5558 }
5559 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005560 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005561 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005562 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005563 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005564
5565 mpClientInterface->suspendOutput(a2dpOutput);
5566 mA2dpSuspended = true;
5567 }
5568 }
5569}
5570
François Gaffie11d30102018-11-02 16:09:09 +01005571DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5572 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
François Gaffie11d30102018-11-02 16:09:09 +01005574 DeviceVector devices;
5575
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005576 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005577 if (index >= 0) {
5578 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005579 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005580 ALOGV("%s device %s forced by patch %d", __func__,
5581 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5582 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005583 }
5584 }
5585
Dean Wheatley514b4312020-06-17 21:45:00 +10005586 // Do not retrieve engine device for outputs through MSD
5587 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5588 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5589 return outputDesc->devices();
5590 }
5591
Eric Laurent97ac8712018-07-27 18:59:02 -07005592 // Honor explicit routing requests only if no client using default routing is active on this
5593 // input: a specific app can not force routing for other apps by setting a preferred device.
5594 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005595 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005596 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005597 if (device != nullptr) {
5598 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005599 }
5600
François Gaffiea807ef92018-11-05 10:44:33 +01005601 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5602 // of setForceUse / Default Bus device here
5603 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5604 if (device != nullptr) {
5605 return DeviceVector(device);
5606 }
5607
François Gaffiec005e562018-11-06 15:04:49 +01005608 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5609 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5610 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005611
François Gaffiec005e562018-11-06 15:04:49 +01005612 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005613 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5614 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005615 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005616 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5617 outputDesc->isStrategyActive(productStrategy)) {
5618 // Retrieval of devices for voice DL is done on primary output profile, cannot
5619 // check the route (would force modifying configuration file for this profile)
5620 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5621 break;
5622 }
Eric Laurente552edb2014-03-10 17:42:56 -07005623 }
François Gaffiec005e562018-11-06 15:04:49 +01005624 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005625 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005626}
5627
François Gaffie11d30102018-11-02 16:09:09 +01005628sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5629 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005630{
François Gaffie11d30102018-11-02 16:09:09 +01005631 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005632
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005633 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005634 if (index >= 0) {
5635 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005636 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005637 ALOGV("getNewInputDevice() device %s forced by patch %d",
5638 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5639 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005640 }
5641 }
5642
Eric Laurent97ac8712018-07-27 18:59:02 -07005643 // Honor explicit routing requests only if no client using default routing is active on this
5644 // input: a specific app can not force routing for other apps by setting a preferred device.
5645 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005646 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5647 if (device != nullptr) {
5648 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005649 }
5650
Eric Laurentdc95a252018-04-12 12:46:56 -07005651 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005652 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005653 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5654 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5655 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005656 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005657 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005658 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005659 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005660
Eric Laurente552edb2014-03-10 17:42:56 -07005661 return device;
5662}
5663
Eric Laurent794fde22016-03-11 09:50:45 -08005664bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5665 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005666 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005667}
5668
Eric Laurente0720872014-03-11 09:30:41 -07005669audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005670 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005671 // getOutputDevicesForStream's behavior for invalid streams.
5672 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5673 // device for music stream), but we want to return the empty set.
5674 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005675 return AUDIO_DEVICE_NONE;
5676 }
François Gaffie11d30102018-11-02 16:09:09 +01005677 DeviceVector activeDevices;
5678 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005679 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5680 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005681 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005682 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005683 }
François Gaffiec005e562018-11-06 15:04:49 +01005684 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005685 devices.merge(curDevices);
5686 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005687 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005688 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005689 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005690 }
5691 }
Eric Laurente552edb2014-03-10 17:42:56 -07005692 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005693
Eric Laurentb0688d62018-08-14 15:49:18 -07005694 // Favor devices selected on active streams if any to report correct device in case of
5695 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005696 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005697 devices = activeDevices;
5698 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005699 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5700 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005701 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005702 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005703 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005704 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005705 }
jiabin9a3361e2019-10-01 09:38:30 -07005706 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5707 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005708}
5709
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005710status_t AudioPolicyManager::getDevicesForAttributes(
5711 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5712 if (devices == nullptr) {
5713 return BAD_VALUE;
5714 }
5715 // check dynamic policies but only for primary descriptors (secondary not used for audible
5716 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005717 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005718 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005719 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005720 if (status != OK) {
5721 return status;
5722 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005723 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5724 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5725 devices->push_back(device);
5726 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005727 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005728 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5729 for (const auto& device : curDevices) {
5730 devices->push_back(device->getDeviceTypeAddr());
5731 }
5732 return NO_ERROR;
5733}
5734
Eric Laurente0720872014-03-11 09:30:41 -07005735void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005736 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005737 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005738 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005739 updateDevicesAndOutputs();
5740 break;
5741 default:
5742 break;
5743 }
5744}
5745
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005746uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005747
5748 // skip beacon mute management if a dedicated TTS output is available
5749 if (mTtsOutputAvailable) {
5750 return 0;
5751 }
5752
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005753 switch(event) {
5754 case STARTING_OUTPUT:
5755 mBeaconMuteRefCount++;
5756 break;
5757 case STOPPING_OUTPUT:
5758 if (mBeaconMuteRefCount > 0) {
5759 mBeaconMuteRefCount--;
5760 }
5761 break;
5762 case STARTING_BEACON:
5763 mBeaconPlayingRefCount++;
5764 break;
5765 case STOPPING_BEACON:
5766 if (mBeaconPlayingRefCount > 0) {
5767 mBeaconPlayingRefCount--;
5768 }
5769 break;
5770 }
5771
5772 if (mBeaconMuteRefCount > 0) {
5773 // any playback causes beacon to be muted
5774 return setBeaconMute(true);
5775 } else {
5776 // no other playback: unmute when beacon starts playing, mute when it stops
5777 return setBeaconMute(mBeaconPlayingRefCount == 0);
5778 }
5779}
5780
5781uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5782 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5783 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5784 // keep track of muted state to avoid repeating mute/unmute operations
5785 if (mBeaconMuted != mute) {
5786 // mute/unmute AUDIO_STREAM_TTS on all outputs
5787 ALOGV("\t muting %d", mute);
5788 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005789 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005790 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005791 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005792 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005793 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005794 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005795 maxLatency = latency;
5796 }
5797 }
5798 mBeaconMuted = mute;
5799 return maxLatency;
5800 }
5801 return 0;
5802}
5803
Eric Laurente0720872014-03-11 09:30:41 -07005804void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005805{
François Gaffiec005e562018-11-06 15:04:49 +01005806 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005807 mPreviousOutputs = mOutputs;
5808}
5809
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005810uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005811 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005812 uint32_t delayMs)
5813{
5814 // mute/unmute strategies using an incompatible device combination
5815 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5816 // if unmuting, unmute only after the specified delay
5817 if (outputDesc->isDuplicated()) {
5818 return 0;
5819 }
5820
5821 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005822 DeviceVector devices = outputDesc->devices();
5823 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005824
François Gaffiec005e562018-11-06 15:04:49 +01005825 auto productStrategies = mEngine->getOrderedProductStrategies();
5826 for (const auto &productStrategy : productStrategies) {
5827 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5828 DeviceVector curDevices =
5829 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5830 curDevices = curDevices.filter(outputDesc->supportedDevices());
5831 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005832 bool doMute = false;
5833
François Gaffiec005e562018-11-06 15:04:49 +01005834 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005835 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005836 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5837 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005838 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005839 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005840 }
Eric Laurent99401132014-05-07 19:48:15 -07005841 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005842 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005843 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005844 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005845 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005846 continue;
5847 }
François Gaffiec005e562018-11-06 15:04:49 +01005848 ALOGVV("%s() %s (curDevice %s)", __func__,
5849 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5850 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5851 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005852 if (mute) {
5853 // FIXME: should not need to double latency if volume could be applied
5854 // immediately by the audioflinger mixer. We must account for the delay
5855 // between now and the next time the audioflinger thread for this output
5856 // will process a buffer (which corresponds to one buffer size,
5857 // usually 1/2 or 1/4 of the latency).
5858 if (muteWaitMs < desc->latency() * 2) {
5859 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005860 }
5861 }
5862 }
5863 }
5864 }
5865 }
5866
Eric Laurent99401132014-05-07 19:48:15 -07005867 // temporary mute output if device selection changes to avoid volume bursts due to
5868 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005869 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005870 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5871 // temporary mute duration is conservatively set to 4 times the reported latency
5872 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5873 if (muteWaitMs < tempMuteWaitMs) {
5874 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005875 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005876 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5877 // make sure that we do not start the temporary mute period too early in case of
5878 // delayed device change
5879 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5880 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005881 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005882 }
5883 }
5884
Eric Laurente552edb2014-03-10 17:42:56 -07005885 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5886 if (muteWaitMs > delayMs) {
5887 muteWaitMs -= delayMs;
5888 usleep(muteWaitMs * 1000);
5889 return muteWaitMs;
5890 }
5891 return 0;
5892}
5893
François Gaffie11d30102018-11-02 16:09:09 +01005894uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5895 const DeviceVector &devices,
5896 bool force,
5897 int delayMs,
5898 audio_patch_handle_t *patchHandle,
5899 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005900{
François Gaffie11d30102018-11-02 16:09:09 +01005901 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005902 uint32_t muteWaitMs;
5903
5904 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005905 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5906 nullptr /* patchHandle */, requiresMuteCheck);
5907 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5908 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005909 return muteWaitMs;
5910 }
Eric Laurente552edb2014-03-10 17:42:56 -07005911
5912 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005913 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005914 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005915
François Gaffie11d30102018-11-02 16:09:09 +01005916 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5917
5918 if (!filteredDevices.isEmpty()) {
5919 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005920 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005921
5922 // if the outputs are not materially active, there is no need to mute.
5923 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005924 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005925 } else {
5926 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5927 muteWaitMs = 0;
5928 }
Eric Laurente552edb2014-03-10 17:42:56 -07005929
Eric Laurent79ea9582020-06-11 18:49:24 -07005930 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5931 // output profile or if new device is not supported AND previous device(s) is(are) still
5932 // available (otherwise reset device must be done on the output)
5933 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5934 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5935 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5936 // restore previous device after evaluating strategy mute state
5937 outputDesc->setDevices(prevDevices);
5938 return muteWaitMs;
5939 }
5940
Eric Laurente552edb2014-03-10 17:42:56 -07005941 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005942 // the requested device is AUDIO_DEVICE_NONE
5943 // OR the requested device is the same as current device
5944 // AND force is not specified
5945 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005946 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005947 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005948 !force && outputDesc->getPatchHandle() != 0) {
5949 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5950 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005951 return muteWaitMs;
5952 }
5953
François Gaffie11d30102018-11-02 16:09:09 +01005954 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005955
Eric Laurente552edb2014-03-10 17:42:56 -07005956 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005957 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005958 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005959 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005960 PatchBuilder patchBuilder;
5961 patchBuilder.addSource(outputDesc);
5962 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5963 for (const auto &filteredDevice : filteredDevices) {
5964 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005965 }
5966
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005967 // Add half reported latency to delayMs when muteWaitMs is null in order
5968 // to avoid disordered sequence of muting volume and changing devices.
5969 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5970 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005971 }
Eric Laurente552edb2014-03-10 17:42:56 -07005972
5973 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005974 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005975
5976 return muteWaitMs;
5977}
5978
Eric Laurentc75307b2015-03-17 15:29:32 -07005979status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005980 int delayMs,
5981 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005982{
Eric Laurent6a94d692014-05-20 11:18:06 -07005983 ssize_t index;
5984 if (patchHandle) {
5985 index = mAudioPatches.indexOfKey(*patchHandle);
5986 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005987 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005988 }
5989 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005990 return INVALID_OPERATION;
5991 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005992 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005993 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005994 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005995 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01005996 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005997 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005998 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005999 return status;
6000}
6001
6002status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006003 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006004 bool force,
6005 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006006{
6007 status_t status = NO_ERROR;
6008
Eric Laurent1f2f2232014-06-02 12:01:23 -07006009 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006010 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6011 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006012
François Gaffie11d30102018-11-02 16:09:09 +01006013 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006014 PatchBuilder patchBuilder;
6015 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006016 // AUDIO_SOURCE_HOTWORD is for internal use only:
6017 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006018 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6019 auto result = usecase;
6020 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6021 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6022 }
6023 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006024 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006025 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006026 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006027 }
6028 }
6029 return status;
6030}
6031
Eric Laurent6a94d692014-05-20 11:18:06 -07006032status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6033 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006034{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006035 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006036 ssize_t index;
6037 if (patchHandle) {
6038 index = mAudioPatches.indexOfKey(*patchHandle);
6039 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006040 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006041 }
6042 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006043 return INVALID_OPERATION;
6044 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006045 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006046 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006047 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006048 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006049 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006050 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006051 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006052 return status;
6053}
6054
François Gaffie11d30102018-11-02 16:09:09 +01006055sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006056 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006057 audio_format_t& format,
6058 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006059 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006060{
6061 // Choose an input profile based on the requested capture parameters: select the first available
6062 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006063 //
6064 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6065 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006066
Glenn Kasten730b9262018-03-29 15:01:26 -07006067 sp<IOProfile> firstInexact;
6068 uint32_t updatedSamplingRate = 0;
6069 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6070 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006071 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006072 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006073 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006074 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006075 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006076 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006077 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006078 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006079 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006080 &channelMask /*updatedChannelMask*/,
6081 // FIXME ugly cast
6082 (audio_output_flags_t) flags,
6083 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006084 return profile;
6085 }
François Gaffie11d30102018-11-02 16:09:09 +01006086 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006087 samplingRate,
6088 &updatedSamplingRate,
6089 format,
6090 &updatedFormat,
6091 channelMask,
6092 &updatedChannelMask,
6093 // FIXME ugly cast
6094 (audio_output_flags_t) flags,
6095 false /*exactMatchRequiredForInputFlags*/)) {
6096 firstInexact = profile;
6097 }
6098
Eric Laurente552edb2014-03-10 17:42:56 -07006099 }
6100 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006101 if (firstInexact != nullptr) {
6102 samplingRate = updatedSamplingRate;
6103 format = updatedFormat;
6104 channelMask = updatedChannelMask;
6105 return firstInexact;
6106 }
Eric Laurente552edb2014-03-10 17:42:56 -07006107 return NULL;
6108}
6109
François Gaffieaaac0fd2018-11-22 17:56:39 +01006110float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6111 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006112 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006113 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006114{
jiabin9a3361e2019-10-01 09:38:30 -07006115 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006116
6117 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6118 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6119 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6120 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006121 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6122 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6123 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6124 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006125 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006126
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006127 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006128 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6129 mOutputs.isActive(ringVolumeSrc, 0)) {
6130 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006131 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006132 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006133 }
6134
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006135 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006136 if ((volumeSource != callVolumeSrc && (isInCall() ||
6137 mOutputs.isActiveLocally(callVolumeSrc))) &&
6138 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6139 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6140 volumeSource == alarmVolumeSrc ||
6141 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6142 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6143 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006144 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006145 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006146 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006147 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006148 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006149 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006150 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6151 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6152 // programmatically muted.
6153 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6154 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6155 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006156 bool exemptFromCapping =
6157 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6158 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006159 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6160 volumeSource, volumeDb);
6161 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006162 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6163 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6164 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006165 }
6166 }
Eric Laurente552edb2014-03-10 17:42:56 -07006167 // if a headset is connected, apply the following rules to ring tones and notifications
6168 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006169 // - always attenuate notifications volume by 6dB
6170 // - attenuate ring tones volume by 6dB unless music is not playing and
6171 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006172 // - if music is playing, always limit the volume to current music volume,
6173 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006174 if (!Intersection(deviceTypes,
6175 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6176 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006177 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6178 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006179 ((volumeSource == alarmVolumeSrc ||
6180 volumeSource == ringVolumeSrc) ||
6181 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6182 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6183 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6184 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6185 curves.canBeMuted()) {
6186
Eric Laurente552edb2014-03-10 17:42:56 -07006187 // when the phone is ringing we must consider that music could have been paused just before
6188 // by the music application and behave as if music was active if the last music track was
6189 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006190 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006191 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006192 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006193 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006194 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6195 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006196 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006197 float musicVolDb = computeVolume(musicCurves,
6198 musicVolumeSrc,
6199 musicCurves.getVolumeIndex(musicDevice),
6200 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006201 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6202 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6203 if (volumeDb > minVolDb) {
6204 volumeDb = minVolDb;
6205 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006206 }
jiabin9a3361e2019-10-01 09:38:30 -07006207 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6208 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006209 // on A2DP, also ensure notification volume is not too low compared to media when
6210 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006211 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006212 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006213 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6214 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006215 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6216 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006217 }
6218 }
jiabin9a3361e2019-10-01 09:38:30 -07006219 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006220 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006221 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006222 }
6223 }
6224
François Gaffie43c73442018-11-08 08:21:55 +01006225 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006226}
6227
Eric Laurent3839bc02018-07-10 18:33:34 -07006228int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006229 VolumeSource fromVolumeSource,
6230 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006231{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006232 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006233 return srcIndex;
6234 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006235 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6236 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006237 float minSrc = (float)srcCurves.getVolumeIndexMin();
6238 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6239 float minDst = (float)dstCurves.getVolumeIndexMin();
6240 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006241
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006242 // preserve mute request or correct range
6243 if (srcIndex < minSrc) {
6244 if (srcIndex == 0) {
6245 return 0;
6246 }
6247 srcIndex = minSrc;
6248 } else if (srcIndex > maxSrc) {
6249 srcIndex = maxSrc;
6250 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006251 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6252}
6253
François Gaffieaaac0fd2018-11-22 17:56:39 +01006254status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6255 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006256 int index,
6257 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006258 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006259 int delayMs,
6260 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006261{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006262 // do not change actual attributes volume if the attributes is muted
6263 if (outputDesc->isMuted(volumeSource)) {
6264 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6265 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006266 return NO_ERROR;
6267 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006268 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6269 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6270 bool isVoiceVolSrc = callVolSrc == volumeSource;
6271 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6272
Eric Laurent2517af32020-11-25 15:31:27 +01006273 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006274 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006275 // if sco and call follow same curves, bypass forceUseForComm
6276 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006277 ((isVoiceVolSrc && isScoRequested) ||
6278 (isBtScoVolSrc && !isScoRequested))) {
6279 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6280 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006281 // Do not return an error here as AudioService will always set both voice call
6282 // and bluetooth SCO volumes due to stream aliasing.
6283 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006284 }
jiabin9a3361e2019-10-01 09:38:30 -07006285 if (deviceTypes.empty()) {
6286 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006287 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006288
jiabin9a3361e2019-10-01 09:38:30 -07006289 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6290 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006291 // Force VoIP volume to max for bluetooth SCO device except if muted
6292 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006293 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006294 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006295 }
jiabin9a3361e2019-10-01 09:38:30 -07006296 outputDesc->setVolume(
6297 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006298
François Gaffieaaac0fd2018-11-22 17:56:39 +01006299 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006300 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006301 // 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 +01006302 if (isVoiceVolSrc) {
6303 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006304 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006305 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006306 }
Eric Laurent18fba842016-03-31 14:41:26 -07006307 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006308 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6309 mLastVoiceVolume = voiceVolume;
6310 }
6311 }
Eric Laurente552edb2014-03-10 17:42:56 -07006312 return NO_ERROR;
6313}
6314
Eric Laurentc75307b2015-03-17 15:29:32 -07006315void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006316 const DeviceTypeSet& deviceTypes,
6317 int delayMs,
6318 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006319{
jiabincd510522020-01-22 09:40:55 -08006320 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006321 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6322 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6323 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006324 curves.getVolumeIndex(deviceTypes),
6325 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006326 }
6327}
6328
François Gaffiec005e562018-11-06 15:04:49 +01006329void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6330 bool on,
6331 const sp<AudioOutputDescriptor>& outputDesc,
6332 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006333 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006334{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006335 std::vector<VolumeSource> sourcesToMute;
6336 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6337 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6338 toString(attributes).c_str(), on, outputDesc->getId());
6339 VolumeSource source = toVolumeSource(attributes);
6340 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6341 sourcesToMute.push_back(source);
6342 }
Eric Laurente552edb2014-03-10 17:42:56 -07006343 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006344 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006345 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006346 }
6347
Eric Laurente552edb2014-03-10 17:42:56 -07006348}
6349
François Gaffieaaac0fd2018-11-22 17:56:39 +01006350void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6351 bool on,
6352 const sp<AudioOutputDescriptor>& outputDesc,
6353 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006354 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006355{
jiabin9a3361e2019-10-01 09:38:30 -07006356 if (deviceTypes.empty()) {
6357 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006358 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006359 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006360 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006361 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006362 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006363 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6364 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6365 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006366 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006367 }
6368 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006369 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6370 // ignored
6371 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006372 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006373 if (!outputDesc->isMuted(volumeSource)) {
6374 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006375 return;
6376 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006377 if (outputDesc->decMuteCount(volumeSource) == 0) {
6378 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006379 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006380 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006381 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006382 delayMs);
6383 }
6384 }
6385}
6386
François Gaffie53615e22015-03-19 09:24:12 +01006387bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6388{
François Gaffiec005e562018-11-06 15:04:49 +01006389 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006390 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6391 return true;
6392 }
6393
6394 // has known usage?
6395 switch (paa->usage) {
6396 case AUDIO_USAGE_UNKNOWN:
6397 case AUDIO_USAGE_MEDIA:
6398 case AUDIO_USAGE_VOICE_COMMUNICATION:
6399 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6400 case AUDIO_USAGE_ALARM:
6401 case AUDIO_USAGE_NOTIFICATION:
6402 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6403 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6404 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6405 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6406 case AUDIO_USAGE_NOTIFICATION_EVENT:
6407 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6408 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6409 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6410 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006411 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006412 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006413 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006414 case AUDIO_USAGE_EMERGENCY:
6415 case AUDIO_USAGE_SAFETY:
6416 case AUDIO_USAGE_VEHICLE_STATUS:
6417 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006418 break;
6419 default:
6420 return false;
6421 }
6422 return true;
6423}
6424
François Gaffie2110e042015-03-24 08:41:51 +01006425audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6426{
6427 return mEngine->getForceUse(usage);
6428}
6429
6430bool AudioPolicyManager::isInCall()
6431{
6432 return isStateInCall(mEngine->getPhoneState());
6433}
6434
6435bool AudioPolicyManager::isStateInCall(int state)
6436{
6437 return is_state_in_call(state);
6438}
6439
Eric Laurent74b71512019-11-06 17:21:57 -08006440bool AudioPolicyManager::isCallAudioAccessible()
6441{
6442 audio_mode_t mode = mEngine->getPhoneState();
6443 return (mode == AUDIO_MODE_IN_CALL)
6444 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6445 || (mode == AUDIO_MODE_CALL_SCREEN);
6446}
6447
Eric Laurentd60560a2015-04-10 11:31:20 -07006448void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6449{
6450 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006451 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6452 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6453 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6454 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006455 }
6456 }
6457
6458 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6459 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6460 bool release = false;
6461 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6462 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6463 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6464 source->ext.device.type == deviceDesc->type()) {
6465 release = true;
6466 }
6467 }
6468 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6469 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6470 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6471 sink->ext.device.type == deviceDesc->type()) {
6472 release = true;
6473 }
6474 }
6475 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006476 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6477 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006478 }
6479 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006480
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006481 mInputs.clearSessionRoutesForDevice(deviceDesc);
6482
Francois Gaffie716e1432019-01-14 16:58:59 +01006483 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006484}
6485
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006486void AudioPolicyManager::modifySurroundFormats(
6487 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006488 std::unordered_set<audio_format_t> enforcedSurround(
6489 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006490 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6491 for (const auto& pair : mConfig.getSurroundFormats()) {
6492 allSurround.insert(pair.first);
6493 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6494 }
Phil Burk09bc4612016-02-24 15:58:15 -08006495
6496 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6497 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006498 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006499 // This is the resulting set of formats depending on the surround mode:
6500 // 'all surround' = allSurround
6501 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6502 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6503 // 'manual surround' = mManualSurroundFormats
6504 // AUTO: formats v 'enforced surround'
6505 // ALWAYS: formats v 'all surround' v 'enforced surround'
6506 // NEVER: formats ^ 'non-surround'
6507 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006508
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006509 std::unordered_set<audio_format_t> formatSet;
6510 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6511 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006512 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006513 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006514 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006515 formatSet.insert(*formatIter);
6516 }
6517 }
6518 } else {
6519 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6520 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006521 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006522
jiabin81772902018-04-02 17:52:27 -07006523 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006524 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006525 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6526 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6527 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006528 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006529 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6530 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6531 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006532 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006533 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006534 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006535 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006536 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006537 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006538}
6539
jiabin06e4bab2019-07-29 10:13:34 -07006540void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6541 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006542 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6543 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6544
6545 // If NEVER, then remove support for channelMasks > stereo.
6546 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006547 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6548 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006549 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6550 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006551 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006552 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006553 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006554 }
6555 }
jiabin81772902018-04-02 17:52:27 -07006556 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6557 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6558 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006559 bool supports5dot1 = false;
6560 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006561 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006562 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6563 supports5dot1 = true;
6564 break;
6565 }
6566 }
6567 // If not then add 5.1 support.
6568 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006569 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006570 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006571 }
Phil Burk09bc4612016-02-24 15:58:15 -08006572 }
6573}
6574
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006575void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006576 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006577 AudioProfileVector &profiles)
6578{
6579 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006580 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006581
François Gaffie112b0af2015-11-19 16:13:25 +01006582 // Format MUST be checked first to update the list of AudioProfile
6583 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006584 reply = mpClientInterface->getParameters(
6585 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006586 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006587 AudioParameter repliedParameters(reply);
6588 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006589 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006590 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6591 return;
6592 }
Phil Burk09bc4612016-02-24 15:58:15 -08006593 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006594 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006595 if (device == AUDIO_DEVICE_OUT_HDMI
6596 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006597 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006598 }
jiabin3e277cc2019-09-10 14:27:34 -07006599 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006600 }
François Gaffie112b0af2015-11-19 16:13:25 +01006601
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006602 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006603 ChannelMaskSet channelMasks;
6604 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006605 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006606 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006607
6608 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006609 reply = mpClientInterface->getParameters(
6610 ioHandle,
6611 requestedParameters.toString() + ";" +
6612 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006613 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006614 AudioParameter repliedParameters(reply);
6615 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006616 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006617 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006618 }
6619 }
6620 if (profiles.hasDynamicChannelsFor(format)) {
6621 reply = mpClientInterface->getParameters(ioHandle,
6622 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006623 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006624 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006625 AudioParameter repliedParameters(reply);
6626 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006627 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006628 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006629 if (device == AUDIO_DEVICE_OUT_HDMI
6630 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006631 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006632 }
François Gaffie112b0af2015-11-19 16:13:25 +01006633 }
6634 }
jiabin3e277cc2019-09-10 14:27:34 -07006635 addDynamicAudioProfileAndSort(
6636 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006637 }
6638}
Eric Laurentd60560a2015-04-10 11:31:20 -07006639
Mikhail Naganovdc769682018-05-04 15:34:08 -07006640status_t AudioPolicyManager::installPatch(const char *caller,
6641 audio_patch_handle_t *patchHandle,
6642 AudioIODescriptorInterface *ioDescriptor,
6643 const struct audio_patch *patch,
6644 int delayMs)
6645{
6646 ssize_t index = mAudioPatches.indexOfKey(
6647 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6648 *patchHandle : ioDescriptor->getPatchHandle());
6649 sp<AudioPatch> patchDesc;
6650 status_t status = installPatch(
6651 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6652 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006653 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006654 }
6655 return status;
6656}
6657
6658status_t AudioPolicyManager::installPatch(const char *caller,
6659 ssize_t index,
6660 audio_patch_handle_t *patchHandle,
6661 const struct audio_patch *patch,
6662 int delayMs,
6663 uid_t uid,
6664 sp<AudioPatch> *patchDescPtr)
6665{
6666 sp<AudioPatch> patchDesc;
6667 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6668 if (index >= 0) {
6669 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006670 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006671 }
6672
6673 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6674 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6675 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6676 if (status == NO_ERROR) {
6677 if (index < 0) {
6678 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006679 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006680 } else {
6681 patchDesc->mPatch = *patch;
6682 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006683 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006684 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006685 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006686 }
6687 nextAudioPortGeneration();
6688 mpClientInterface->onAudioPatchListUpdate();
6689 }
6690 if (patchDescPtr) *patchDescPtr = patchDesc;
6691 return status;
6692}
6693
jiabinbce0c1d2020-10-05 11:20:18 -07006694bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6695{
6696 const TrackClientVector activeClients = output->getActiveClients();
6697 if (activeClients.empty()) {
6698 return true;
6699 }
6700 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6701 if (index < 0) {
6702 ALOGE("%s, no audio patch found while there are active clients on output %d",
6703 __func__, output->getId());
6704 return false;
6705 }
6706 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6707 DeviceVector routedDevices;
6708 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6709 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6710 patchDesc->mPatch.sinks[i].id);
6711 if (device == nullptr) {
6712 ALOGE("%s, no audio device found with id(%d)",
6713 __func__, patchDesc->mPatch.sinks[i].id);
6714 return false;
6715 }
6716 routedDevices.add(device);
6717 }
6718 for (const auto& client : activeClients) {
6719 // TODO: b/175343099 only travel the valid client
6720 sp<DeviceDescriptor> preferredDevice =
6721 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6722 if (mEngine->getOutputDevicesForAttributes(
6723 client->attributes(), preferredDevice, false) == routedDevices) {
6724 return false;
6725 }
6726 }
6727 return true;
6728}
6729
6730sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6731 const sp<IOProfile>& profile, const DeviceVector& devices)
6732{
6733 for (const auto& device : devices) {
6734 // TODO: This should be checking if the profile supports the device combo.
6735 if (!profile->supportsDevice(device)) {
6736 return nullptr;
6737 }
6738 }
6739 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
6740 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6741 status_t status = desc->open(nullptr, devices,
6742 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6743 if (status != NO_ERROR) {
6744 return nullptr;
6745 }
6746
6747 // Here is where the out_set_parameters() for card & device gets called
6748 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
6749 const audio_devices_t deviceType = device->type();
6750 const String8 &address = String8(device->address().c_str());
6751 if (!address.isEmpty()) {
6752 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
6753 mpClientInterface->setParameters(output, String8(param));
6754 free(param);
6755 }
6756 updateAudioProfiles(device, output, profile->getAudioProfiles());
6757 if (!profile->hasValidAudioProfile()) {
6758 ALOGW("%s() missing param", __func__);
6759 desc->close();
6760 return nullptr;
6761 } else if (profile->hasDynamicAudioProfile()) {
6762 desc->close();
6763 output = AUDIO_IO_HANDLE_NONE;
6764 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
6765 profile->pickAudioProfile(
6766 config.sample_rate, config.channel_mask, config.format);
6767 config.offload_info.sample_rate = config.sample_rate;
6768 config.offload_info.channel_mask = config.channel_mask;
6769 config.offload_info.format = config.format;
6770
6771 status = desc->open(&config, devices,
6772 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
6773 if (status != NO_ERROR) {
6774 return nullptr;
6775 }
6776 }
6777
6778 addOutput(output, desc);
6779 if (audio_is_remote_submix_device(deviceType) && address != "0") {
6780 sp<AudioPolicyMix> policyMix;
6781 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
6782 policyMix->setOutput(desc);
6783 desc->mPolicyMix = policyMix;
6784 } else {
6785 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
6786 address.string());
6787 }
6788
6789 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
6790 // no duplicated output for direct outputs and
6791 // outputs used by dynamic policy mixes
6792 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
6793
6794 //TODO: configure audio effect output stage here
6795
6796 // open a duplicating output thread for the new output and the primary output
6797 sp<SwAudioOutputDescriptor> dupOutputDesc =
6798 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
6799 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
6800 if (status == NO_ERROR) {
6801 // add duplicated output descriptor
6802 addOutput(duplicatedOutput, dupOutputDesc);
6803 } else {
6804 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
6805 mPrimaryOutput->mIoHandle, output);
6806 desc->close();
6807 removeOutput(output);
6808 nextAudioPortGeneration();
6809 return nullptr;
6810 }
6811 }
6812 return desc;
6813}
6814
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006815} // namespace android