blob: d7c7b4d029bea569680428a5fe0da10e7c1a3218 [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
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080084 const char *device_name,
85 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -070086{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080087 status_t status = setDeviceConnectionStateInt(device, state, device_address,
88 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080089 nextAudioPortGeneration();
90 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080091}
92
François Gaffie11d30102018-11-02 16:09:09 +010093void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
94 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020095{
François Gaffie11d30102018-11-02 16:09:09 +010096 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020097 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070098 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010099 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200100 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
101}
102
François Gaffie11d30102018-11-02 16:09:09 +0100103status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800104 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800105 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 const char *device_name,
107 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800109 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
110 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700111
112 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100113 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700114
François Gaffie11d30102018-11-02 16:09:09 +0100115 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800116 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100117 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
118 if (device == 0) {
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100123 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700124 SortedVector <audio_io_handle_t> outputs;
125
François Gaffie11d30102018-11-02 16:09:09 +0100126 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127
Eric Laurente552edb2014-03-10 17:42:56 -0700128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 switch (state)
132 {
133 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100136 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700137 return INVALID_OPERATION;
138 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800139 ALOGV("%s() connecting device %s format %x",
140 __func__, device->toString().c_str(), encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // register new device as available
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800143 index = mAvailableOutputDevices.add(device);
144 if (index >= 0) {
145 sp<HwModule> module = mHwModules.getModuleForDevice(device, encodedFormat);
146 if (module == 0) {
147 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
148 device->toString().c_str());
149 mAvailableOutputDevices.remove(device);
150 return INVALID_OPERATION;
151 }
152 ALOGV("setDeviceConnectionState() module name=%s", module->getName());
153 mAvailableOutputDevices[index]->attach(module);
154 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100160 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200161
François Gaffie11d30102018-11-02 16:09:09 +0100162 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
163 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200164
Francois Gaffie716e1432019-01-14 16:58:59 +0100165 mHwModules.cleanUpForDevice(device);
166
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700168 return INVALID_OPERATION;
169 }
François Gaffie2110e042015-03-24 08:41:51 +0100170 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100171 mEngine->setDeviceConnectionState(device, state);
François Gaffie2110e042015-03-24 08:41:51 +0100172
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 // outputs should never be empty here
174 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
175 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100176 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100182 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700183 return INVALID_OPERATION;
184 }
185
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100189 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100192 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
François Gaffie11d30102018-11-02 16:09:09 +0100194 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100195
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800196 // Reset active device codec
197 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
198
François Gaffie2110e042015-03-24 08:41:51 +0100199 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100200 mEngine->setDeviceConnectionState(device, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700201 } break;
202
203 default:
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return BAD_VALUE;
206 }
207
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 checkForDeviceAndOutputChanges([&]() {
209 // outputs must be closed after checkOutputForAllStrategies() is executed
210 if (!outputs.isEmpty()) {
211 for (audio_io_handle_t output : outputs) {
212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100213 // close unused outputs after device disconnection or direct outputs that have
214 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
216 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
217 (desc->mDirectOpenCount == 0))) {
218 closeOutput(output);
219 }
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
222 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700224 return false;
225 });
Eric Laurente552edb2014-03-10 17:42:56 -0700226
Eric Laurent87ffa392015-05-22 10:32:38 -0700227 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100228 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
229 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 }
François Gaffie11d30102018-11-02 16:09:09 +0100231 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700232 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
234 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700236 // do not force device change on duplicated output because if device is 0, it will
237 // also force a device 0 for the two outputs it is duplicated to which may override
238 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100239 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100240 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100241 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 // always force when disconnecting (a non-duplicated device)
243 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100244 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700245 }
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
247
Eric Laurentd60560a2015-04-10 11:31:20 -0700248 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100249 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700250 }
251
Eric Laurent72aa32f2014-05-30 18:51:48 -0700252 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700253 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700254 } // end if is output device
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700258 SortedVector <audio_io_handle_t> inputs;
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 switch (state)
262 {
263 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return INVALID_OPERATION;
268 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800269 sp<HwModule> module = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
270 if (module == NULL) {
271 ALOGW("setDeviceConnectionState(): could not find HW module for device %s",
272 device->toString().c_str());
273 return INVALID_OPERATION;
274 }
275
François Gaffie44481e72016-04-20 07:49:57 +0200276 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
277 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100278 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200279
François Gaffie11d30102018-11-02 16:09:09 +0100280 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
281 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100282
283 mHwModules.cleanUpForDevice(device);
284
Eric Laurentd4692962014-05-05 18:13:44 -0700285 return INVALID_OPERATION;
286 }
287
Francois Gaffie716e1432019-01-14 16:58:59 +0100288 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 return NO_MEMORY;
290 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800291
François Gaffie2110e042015-03-24 08:41:51 +0100292 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100293 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700294 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700295
296 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700297 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100299 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700300 return INVALID_OPERATION;
301 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700302
François Gaffie11d30102018-11-02 16:09:09 +0100303 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700304
305 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100306 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700307
François Gaffie11d30102018-11-02 16:09:09 +0100308 checkInputsForDevice(device, state, inputs);
309 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
François Gaffie2110e042015-03-24 08:41:51 +0100311 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100312 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700313 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700314
315 default:
François Gaffie11d30102018-11-02 16:09:09 +0100316 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 return BAD_VALUE;
318 }
319
Eric Laurentd4692962014-05-05 18:13:44 -0700320 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700321 // As the input device list can impact the output device selection, update
322 // getDeviceForStrategy() cache
323 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700324
Eric Laurent87ffa392015-05-22 10:32:38 -0700325 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
327 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 }
329
Eric Laurentd60560a2015-04-10 11:31:20 -0700330 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100331 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700332 }
333
Eric Laurentb52c1522014-05-20 11:27:36 -0700334 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700335 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700337
François Gaffie11d30102018-11-02 16:09:09 +0100338 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700339 return BAD_VALUE;
340}
341
Eric Laurente0720872014-03-11 09:30:41 -0700342audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100343 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700344{
Eric Laurent634b7142016-04-20 13:48:02 -0700345 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800346 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
347 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700348 (strlen(device_address) != 0)/*matchAddress*/);
349
350 if (devDesc == 0) {
351 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
352 device, device_address);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
354 }
François Gaffie53615e22015-03-19 09:24:12 +0100355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100363 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
Eric Laurent634b7142016-04-20 13:48:02 -0700366
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800367 return (deviceVector->getDevice(
368 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800370}
371
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800372status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
373 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800374 const char *device_name,
375 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376{
377 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700378 String8 reply;
379 AudioParameter param;
380 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800382 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
383 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800384
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800385 // connect/disconnect only 1 device at a time
386 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Check if the device is currently connected
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800389 DeviceVector availableDevices = getAvailableOutputDevices();
390 DeviceVector deviceList = availableDevices.getDevicesFromTypeMask(device);
391 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800392 // Nothing to do: device is not connected
393 return NO_ERROR;
394 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800395 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800396
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700397 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800398 // configure codecs.
399 // Handle two specific cases by sending a set parameter to
400 // configure A2DP codecs. No need to toggle device state.
401 // Case 1: A2DP active device switches from primary to primary
402 // module
403 // Case 2: A2DP device config changes on primary module.
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700404 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800405 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
406 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
407 if (availablePrimaryOutputDevices().contains(devDesc) &&
408 (module != 0 && module->getHandle() == primaryHandle)) {
409 reply = mpClientInterface->getParameters(
410 AUDIO_IO_HANDLE_NONE,
411 String8(AudioParameter::keyReconfigA2dpSupported));
412 AudioParameter repliedParameters(reply);
413 repliedParameters.getInt(
414 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
415 if (isReconfigA2dpSupported) {
416 const String8 key(AudioParameter::keyReconfigA2dp);
417 param.add(key, String8("true"));
418 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
419 devDesc->setEncodedFormat(encodedFormat);
420 return NO_ERROR;
421 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700422 }
423 }
424
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800425 // Toggle the device state: UNAVAILABLE -> AVAILABLE
426 // This will force reading again the device configuration
427 status = setDeviceConnectionState(device,
428 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800429 device_address, device_name,
430 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 if (status != NO_ERROR) {
432 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
433 status);
434 return status;
435 }
436
437 status = setDeviceConnectionState(device,
438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800439 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800440 if (status != NO_ERROR) {
441 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
442 status);
443 return status;
444 }
445
446 return NO_ERROR;
447}
448
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800449status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
450 std::vector<audio_format_t> *formats)
451{
452 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
453 char *tok = NULL, *saveptr;
454 status_t status = NO_ERROR;
455 char encoding_formats_list[PROPERTY_VALUE_MAX];
456 audio_format_t format = AUDIO_FORMAT_DEFAULT;
457 // FIXME This list should not come from a property but the supported encoded
458 // formats of declared A2DP devices in primary module
459 property_get("persist.bluetooth.a2dp_offload.cap", encoding_formats_list, "");
460 tok = strtok_r(encoding_formats_list, "-", &saveptr);
461 for (;tok != NULL; tok = strtok_r(NULL, "-", &saveptr)) {
462 if (strcmp(tok, "sbc") == 0) {
463 ALOGV("%s: SBC offload supported\n",__func__);
464 format = AUDIO_FORMAT_SBC;
465 } else if (strcmp(tok, "aptx") == 0) {
466 ALOGV("%s: APTX offload supported\n",__func__);
467 format = AUDIO_FORMAT_APTX;
468 } else if (strcmp(tok, "aptxhd") == 0) {
469 ALOGV("%s: APTX HD offload supported\n",__func__);
470 format = AUDIO_FORMAT_APTX_HD;
471 } else if (strcmp(tok, "ldac") == 0) {
472 ALOGV("%s: LDAC offload supported\n",__func__);
473 format = AUDIO_FORMAT_LDAC;
474 } else if (strcmp(tok, "aac") == 0) {
475 ALOGV("%s: AAC offload supported\n",__func__);
476 format = AUDIO_FORMAT_AAC;
477 } else {
478 ALOGE("%s: undefined token - %s\n",__func__, tok);
479 continue;
480 }
481 formats->push_back(format);
482 }
483 return status;
484}
485
François Gaffie11d30102018-11-02 16:09:09 +0100486uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487{
488 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100489 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700490 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700491
François Gaffie11d30102018-11-02 16:09:09 +0100492 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700493 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700494 }
François Gaffie11d30102018-11-02 16:09:09 +0100495 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
496
Francois Gaffie716e1432019-01-14 16:58:59 +0100497 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffie9eb18552018-11-05 10:33:26 +0100498 auto txSourceDevice = getDeviceAndMixForAttributes(attr);
499 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100501 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700502
503 // release existing RX patch if any
504 if (mCallRxPatch != 0) {
505 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
506 mCallRxPatch.clear();
507 }
508 // release TX patch if any
509 if (mCallTxPatch != 0) {
510 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
511 mCallTxPatch.clear();
512 }
513
François Gaffie9eb18552018-11-05 10:33:26 +0100514 auto telephonyRxModule =
515 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
516 auto telephonyTxModule =
517 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
518 // retrieve Rx Source and Tx Sink device descriptors
519 sp<DeviceDescriptor> rxSourceDevice =
520 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
521 String8(),
522 AUDIO_FORMAT_DEFAULT);
523 sp<DeviceDescriptor> txSinkDevice =
524 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
525 String8(),
526 AUDIO_FORMAT_DEFAULT);
527
528 // RX and TX Telephony device are declared by Primary Audio HAL
529 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
530 (telephonyRxModule->getHalVersionMajor() >= 3)) {
531 if (rxSourceDevice == 0 || txSinkDevice == 0) {
532 // RX / TX Telephony device(s) is(are) not currently available
533 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
534 return muteWaitMs;
535 }
536 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
537 // route between telephony RX to Sink device and Source device to telephony TX
538 const auto &primaryModule = telephonyRxModule;
539 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
540 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
541 } else {
542 // If the RX device is on the primary HW module, then use legacy routing method for
543 // voice calls via setOutputDevice() on primary output.
544 // Otherwise, create two audio patches for TX and RX path.
545 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
546 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // If the TX device is also on the primary HW module, setOutputDevice() will take care
548 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100549 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
550 (txSinkDevice != 0);
551 }
552 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
553 // Otherwise, create two audio patches for TX and RX path.
554 if (!createRxPatch) {
555 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700556 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100557 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700558 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700559 if (createTxPatch) { // create TX path audio patch
François Gaffie9eb18552018-11-05 10:33:26 +0100560 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800561 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700562
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800563 return muteWaitMs;
564}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800566sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100567 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700568 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700569
François Gaffie11d30102018-11-02 16:09:09 +0100570 if (device == nullptr) {
571 return nullptr;
572 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800573 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100574 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 addSource(mAvailableInputDevices.getDevice(
576 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800577 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100578 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 addSink(mAvailableOutputDevices.getDevice(
580 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800581 }
582
François Gaffie11d30102018-11-02 16:09:09 +0100583 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
584 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 device : mAvailableOutputDevices.getDevice(
586 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100587 SortedVector<audio_io_handle_t> outputs =
588 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
589 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800590 // request to reuse existing output stream if one is already opened to reach the target device
591 if (output != AUDIO_IO_HANDLE_NONE) {
592 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100593 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
594 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700595 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800596 }
597
598 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700599 // terminate active capture if on the same HW module as the call TX source device
600 // FIXME: would be better to refine to only inputs whose profile connects to the
601 // call TX device but this information is not in the audio patch and logic here must be
602 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800603 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100604 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700605 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700606 }
607 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700608 }
Eric Laurentdc462862016-07-19 12:29:53 -0700609
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800610 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700611 status_t status = mpClientInterface->createAudioPatch(
612 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800613 ALOGW_IF(status != NO_ERROR,
614 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
615 sp<AudioPatch> audioPatch;
616 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700617 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800618 audioPatch->mAfPatchHandle = afPatchHandle;
619 audioPatch->mUid = mUidCached;
620 }
621 return audioPatch;
622}
623
Mikhail Naganovdc769682018-05-04 15:34:08 -0700624sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100625 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700626 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800627 ALOG_ASSERT(!deviceList.isEmpty(),
628 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700629 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700630}
631
Mikhail Naganov100f0122018-11-29 11:22:16 -0800632audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
633 const DeviceVector& devices, const char *moduleId) const {
634 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
635 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
636}
637
638bool AudioPolicyManager::isDeviceOfModule(
639 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
640 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
641 if (module != 0) {
642 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
643 .indexOf(devDesc) != NAME_NOT_FOUND
644 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
645 .indexOf(devDesc) != NAME_NOT_FOUND;
646 }
647 return false;
648}
649
Eric Laurente0720872014-03-11 09:30:41 -0700650void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700651{
652 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100653 // store previous phone state for management of sonification strategy below
654 int oldState = mEngine->getPhoneState();
655
656 if (mEngine->setPhoneState(state) != NO_ERROR) {
657 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700658 return;
659 }
François Gaffie2110e042015-03-24 08:41:51 +0100660 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700661 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700662 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700663 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800664 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700665 }
666
François Gaffie2110e042015-03-24 08:41:51 +0100667 /**
668 * Switching to or from incall state or switching between telephony and VoIP lead to force
669 * routing command.
670 */
671 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
672 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700673
674 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700675 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700676
Eric Laurente552edb2014-03-10 17:42:56 -0700677 int delayMs = 0;
678 if (isStateInCall(state)) {
679 nsecs_t sysTime = systemTime();
680 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700681 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700682 // mute media and sonification strategies and delay device switch by the largest
683 // latency of any output where either strategy is active.
684 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100685 if ((isStrategyActive(desc, STRATEGY_MEDIA,
686 SONIFICATION_HEADSET_MUSIC_DELAY,
687 sysTime) ||
688 isStrategyActive(desc, STRATEGY_SONIFICATION,
689 SONIFICATION_HEADSET_MUSIC_DELAY,
690 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700691 (delayMs < (int)desc->latency()*2)) {
692 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700693 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700694 setStrategyMute(STRATEGY_MEDIA, true, desc);
695 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700696 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700697 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
698 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700699 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
700 }
701 }
702
Eric Laurent87ffa392015-05-22 10:32:38 -0700703 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100704 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700705 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100706 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 // force routing command to audio hardware when ending call
708 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100709 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
710 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700711 }
Eric Laurente552edb2014-03-10 17:42:56 -0700712
Eric Laurent87ffa392015-05-22 10:32:38 -0700713 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100714 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700715 } else if (oldState == AUDIO_MODE_IN_CALL) {
716 if (mCallRxPatch != 0) {
717 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
718 mCallRxPatch.clear();
719 }
720 if (mCallTxPatch != 0) {
721 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
722 mCallTxPatch.clear();
723 }
François Gaffie11d30102018-11-02 16:09:09 +0100724 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100726 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700729
730 // reevaluate routing on all outputs in case tracks have been started during the call
731 for (size_t i = 0; i < mOutputs.size(); i++) {
732 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100733 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700734 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100735 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700736 }
737 }
738
Eric Laurente552edb2014-03-10 17:42:56 -0700739 if (isStateInCall(state)) {
740 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700741 // force reevaluating accessibility routing when call starts
742 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700743 }
744
745 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700746 if (state == AUDIO_MODE_RINGTONE &&
747 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700748 mLimitRingtoneVolume = true;
749 } else {
750 mLimitRingtoneVolume = false;
751 }
752}
753
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700754audio_mode_t AudioPolicyManager::getPhoneState() {
755 return mEngine->getPhoneState();
756}
757
Eric Laurente0720872014-03-11 09:30:41 -0700758void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100759 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
François Gaffie2110e042015-03-24 08:41:51 +0100761 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700762 if (config == mEngine->getForceUse(usage)) {
763 return;
764 }
Eric Laurente552edb2014-03-10 17:42:56 -0700765
François Gaffie2110e042015-03-24 08:41:51 +0100766 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
767 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
768 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700769 }
François Gaffie2110e042015-03-24 08:41:51 +0100770 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
771 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
772 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700773
774 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700775 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800776
Eric Laurentdc462862016-07-19 12:29:53 -0700777 //FIXME: workaround for truncated touch sounds
778 // to be removed when the problem is handled by system UI
779 uint32_t delayMs = 0;
780 uint32_t waitMs = 0;
781 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
782 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
783 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700784 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100785 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
786 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700787 }
Eric Laurente552edb2014-03-10 17:42:56 -0700788 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700789 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100790 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700791 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffiea807ef92018-11-05 10:44:33 +0100792 // As done in setDeviceConnectionState, we could also fix default device issue by
793 // preventing the force re-routing in case of default dev that distinguishes on address.
794 // Let's give back to engine full device choice decision however.
François Gaffie11d30102018-11-02 16:09:09 +0100795 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700796 }
François Gaffie11d30102018-11-02 16:09:09 +0100797 if (forceVolumeReeval && !newDevices.isEmpty()) {
798 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700799 }
800 }
801
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800802 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100803 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700804 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100805 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800806 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700807 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800808 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700809 }
Eric Laurente552edb2014-03-10 17:42:56 -0700810 }
Eric Laurente552edb2014-03-10 17:42:56 -0700811}
812
Eric Laurente0720872014-03-11 09:30:41 -0700813void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700814{
815 ALOGV("setSystemProperty() property %s, value %s", property, value);
816}
817
Michael Chana94fbb22018-04-24 14:31:19 +1000818// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
819// search to profiles for direct outputs.
820sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100821 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000822 uint32_t samplingRate,
823 audio_format_t format,
824 audio_channel_mask_t channelMask,
825 audio_output_flags_t flags,
826 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700827{
Michael Chana94fbb22018-04-24 14:31:19 +1000828 if (directOnly) {
829 // only retain flags that will drive the direct output profile selection
830 // if explicitly requested
831 static const uint32_t kRelevantFlags =
832 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
833 AUDIO_OUTPUT_FLAG_VOIP_RX);
834 flags =
835 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
836 }
Eric Laurent861a6282015-05-18 15:40:16 -0700837
838 sp<IOProfile> profile;
839
Mikhail Naganovd4120142017-12-06 15:49:22 -0800840 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800841 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100842 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700843 samplingRate, NULL /*updatedSamplingRate*/,
844 format, NULL /*updatedFormat*/,
845 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700846 flags)) {
847 continue;
848 }
849 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100850 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700851 continue;
852 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800853 // reject profiles if connected device does not support codec
854 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
855 continue;
856 }
Michael Chana94fbb22018-04-24 14:31:19 +1000857 if (!directOnly) return curProfile;
858 // when searching for direct outputs, if several profiles are compatible, give priority
859 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100860 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700861 continue;
862 }
863 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100864 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700865 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700866 }
Eric Laurente552edb2014-03-10 17:42:56 -0700867 }
868 }
Eric Laurent861a6282015-05-18 15:40:16 -0700869 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700870}
871
Eric Laurentf4e63452017-11-06 19:31:46 +0000872audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700873{
Eric Laurent3b73df72014-03-11 09:06:29 -0700874 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100875 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800876
877 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
878 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
879 // format, flags, etc. This may result in some discrepancy for functions that utilize
880 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
881 // and AudioSystem::getOutputSamplingRate().
882
François Gaffie11d30102018-11-02 16:09:09 +0100883 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
884 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700885
François Gaffie11d30102018-11-02 16:09:09 +0100886 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
887 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000888 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889}
890
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700891status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
892 const audio_attributes_t *srcAttr,
893 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700894{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700895 if (srcAttr != NULL) {
896 if (!isValidAttributes(srcAttr)) {
897 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
898 __func__,
899 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
900 srcAttr->tags);
901 return BAD_VALUE;
902 }
903 *dstAttr = *srcAttr;
904 } else {
905 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
906 ALOGE("%s: invalid stream type", __func__);
907 return BAD_VALUE;
908 }
909 stream_type_to_audio_attributes(srcStream, dstAttr);
910 }
911 return NO_ERROR;
912}
913
914status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
915 audio_io_handle_t *output,
916 audio_session_t session,
917 const audio_attributes_t *attr,
918 audio_stream_type_t *stream,
919 uid_t uid,
920 const audio_config_t *config,
921 audio_output_flags_t *flags,
922 audio_port_handle_t *selectedDeviceId)
923{
François Gaffie11d30102018-11-02 16:09:09 +0100924 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700925 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100926 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100927 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100928 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700929
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700930 status_t status = getAudioAttributes(resultAttr, attr, *stream);
931 if (status != NO_ERROR) {
932 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700933 }
934
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700935 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700936 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700937 __func__,
938 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100939 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700940
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700941 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700942
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700943 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700944
Scott Randolph7b1fd232018-06-18 15:33:03 -0700945 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100946 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
947 if (requestedDevice != nullptr) {
948 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700949 } else {
950 // If no explict route, is there a matching dynamic policy that applies?
951 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700952 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700953 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
954 if (!audio_has_proportional_frames(config->format)) {
955 return BAD_VALUE;
956 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700957 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700958 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700959 AudioMix *mix = desc->mPolicyMix;
960 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800961 mAvailableOutputDevices.getDevice(
962 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700963 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700964 ALOGV("%s returns output %d", __func__, *output);
965 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700966 }
967
968 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700969 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
970 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700971 return BAD_VALUE;
972 }
François Gaffie11d30102018-11-02 16:09:09 +0100973 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700974 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700975
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700976 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200977 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700978 }
979
Nadav Barb2f18162018-07-18 13:01:53 +0300980 // Set incall music only if device was explicitly set, and fallback to the device which is
981 // chosen by the engine if not.
982 // FIXME: provide a more generic approach which is not device specific and move this back
983 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200984 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100985 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700986 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300987 audio_is_linear_pcm(config->format) &&
988 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100989 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300990 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
991 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700992 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100993 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300994 }
995 }
996
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700997 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800998 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100999 __func__,
1000 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001001
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001002 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001003 if (!msdDevices.isEmpty()) {
1004 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001005 sp<DeviceDescriptor> deviceDesc =
1006 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01001007 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
1008 ALOGV("%s() Using MSD devices %s instead of device %s",
1009 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
1010 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001011 } else {
1012 *output = AUDIO_IO_HANDLE_NONE;
1013 }
1014 }
François Gaffie11d30102018-11-02 16:09:09 +01001015 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001016 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01001017 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001018 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001019 if (*output == AUDIO_IO_HANDLE_NONE) {
1020 return INVALID_OPERATION;
1021 }
Paul McLeanaa981192015-03-21 09:55:15 -07001022
François Gaffie11d30102018-11-02 16:09:09 +01001023 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001024
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001025 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1026
1027 return NO_ERROR;
1028}
1029
1030status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1031 audio_io_handle_t *output,
1032 audio_session_t session,
1033 audio_stream_type_t *stream,
1034 uid_t uid,
1035 const audio_config_t *config,
1036 audio_output_flags_t *flags,
1037 audio_port_handle_t *selectedDeviceId,
1038 audio_port_handle_t *portId)
1039{
1040 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1041 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1042 return INVALID_OPERATION;
1043 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001044 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001045 audio_attributes_t resultAttr;
1046 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1047 config, flags, selectedDeviceId);
1048 if (status != NO_ERROR) {
1049 return status;
1050 }
1051
Eric Laurent8fc147b2018-07-22 19:13:55 -07001052 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1053 .format = config->format,
1054 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001055 *portId = AudioPort::getNextUniqueId();
1056
Eric Laurent8fc147b2018-07-22 19:13:55 -07001057 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001058 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001059 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001060 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -07001061 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001063 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001064
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001065 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +01001066 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001067
Eric Laurente83b55d2014-11-14 10:06:21 -08001068 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001069}
1070
François Gaffie11d30102018-11-02 16:09:09 +01001071audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1072 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001073 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001074 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001075 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001076 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001077{
Andy Hungc88b0642018-04-27 15:42:35 -07001078 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001079 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001080
Eric Laurente552edb2014-03-10 17:42:56 -07001081 // open a direct output if required by specified parameters
1082 //force direct flag if offload flag is set: offloading implies a direct output stream
1083 // and all common behaviors are driven by checking only the direct flag
1084 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001085 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1086 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
Nadav Bar766fb022018-01-07 12:18:03 +02001088 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1089 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001090 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001091 // only allow deep buffering for music stream type
1092 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001093 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001094 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001095 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001096 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1097 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001098 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001099 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001100 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001101 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001102 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001103 audio_is_linear_pcm(config->format) &&
1104 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001105 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001106 AUDIO_OUTPUT_FLAG_DIRECT);
1107 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001108 }
Eric Laurente552edb2014-03-10 17:42:56 -07001109
Nadav Bar766fb022018-01-07 12:18:03 +02001110
Eric Laurentb732cf52014-09-24 19:08:21 -07001111 sp<IOProfile> profile;
1112
1113 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001114 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001115 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001116 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1117 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001118 goto non_direct_output;
1119 }
1120
Andy Hung2ddee192015-12-18 17:34:44 -08001121 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1122 // This prevents creating an offloaded track and tearing it down immediately after start
1123 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001124 // FIXME: We should check the audio session here but we do not have it in this context.
1125 // This may prevent offloading in rare situations where effects are left active by apps
1126 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001127
Nadav Bar766fb022018-01-07 12:18:03 +02001128 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001129 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001130 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001131 config->sample_rate,
1132 config->format,
1133 config->channel_mask,
1134 (audio_output_flags_t)*flags,
1135 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001136 }
1137
Eric Laurent1c333e22014-05-20 10:48:17 -07001138 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001139 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1140 for (size_t i = 0; i < mOutputs.size(); i++) {
1141 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1142 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1143 // reuse direct output if currently open by the same client
1144 // and configured with same parameters
1145 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001146 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001147 (config->channel_mask == desc->mChannelMask) &&
1148 (session == desc->mDirectClientSession)) {
1149 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001150 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001151 mOutputs.keyAt(i), session);
1152 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001153 }
1154 }
1155 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001156
1157 if (!profile->canOpenNewIo()) {
1158 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001159 }
Eric Laurent861a6282015-05-18 15:40:16 -07001160
Eric Laurent3974e3b2017-12-07 17:58:43 -08001161 sp<SwAudioOutputDescriptor> outputDesc =
1162 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001163
François Gaffie11d30102018-11-02 16:09:09 +01001164 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001165
Dean Wheatley3023b382018-08-09 07:42:40 +10001166 // MSD patch may be using the only output stream that can service this request. Release
1167 // MSD patch to prioritize this request over any active output on MSD.
1168 AudioPatchCollection msdPatches = getMsdPatches();
1169 for (size_t i = 0; i < msdPatches.size(); i++) {
1170 const auto& patch = msdPatches[i];
1171 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1172 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1173 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001174 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001175 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1176 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1177 releaseAudioPatch(patch->mHandle, mUidCached);
1178 break;
1179 }
1180 }
1181 }
1182
François Gaffie11d30102018-11-02 16:09:09 +01001183 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001184
1185 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001186 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001187 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001188 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001189 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001190 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1191 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001192 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1193 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001194 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001195 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001196 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001197 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001198 if (audio_is_linear_pcm(config->format) &&
1199 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001200 goto non_direct_output;
1201 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001202 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001203 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001204 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001205 outputDesc->mDirectClientSession = session;
1206
Eric Laurente552edb2014-03-10 17:42:56 -07001207 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001208 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001209 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001210 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001211 return output;
1212 }
1213
Eric Laurentb732cf52014-09-24 19:08:21 -07001214non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001215
1216 // A request for HW A/V sync cannot fallback to a mixed output because time
1217 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001218 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001219 return AUDIO_IO_HANDLE_NONE;
1220 }
1221
Eric Laurente552edb2014-03-10 17:42:56 -07001222 // ignoring channel mask due to downmix capability in mixer
1223
1224 // open a non direct output
1225
1226 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001227 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001228 // get which output is suitable for the specified stream. The actual
1229 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001230 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001231
Eric Laurent8838a382014-09-08 16:44:28 -07001232 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001233 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001234 output = selectOutput(outputs, *flags, config->format,
1235 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001236 }
François Gaffie11d30102018-11-02 16:09:09 +01001237 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001238 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001239 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001240
Eric Laurente552edb2014-03-10 17:42:56 -07001241 return output;
1242}
1243
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001244sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001245 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1246 mAvailableInputDevices);
1247 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1248}
1249
1250DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1251 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1252 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001253}
1254
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001255const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1256 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001257 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1258 if (msdModule != 0) {
1259 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1260 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1261 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1262 const struct audio_port_config *source = &patch->mPatch.sources[j];
1263 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1264 source->ext.device.hw_module == msdModule->getHandle()) {
1265 msdPatches.addAudioPatch(patch->mHandle, patch);
1266 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 }
1268 }
1269 }
1270 return msdPatches;
1271}
1272
François Gaffie11d30102018-11-02 16:09:09 +01001273status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001274 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1275{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001276 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001277 if (msdModule == nullptr) {
1278 ALOGE("%s() unable to get MSD module", __func__);
1279 return NO_INIT;
1280 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001281 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001282 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001283 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001284 return NO_INIT;
1285 }
1286 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1287 if (inputProfiles.isEmpty()) {
1288 ALOGE("%s() no input profiles for MSD module", __func__);
1289 return NO_INIT;
1290 }
1291 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1292 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001293 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001294 return NO_INIT;
1295 }
1296 AudioProfileVector msdProfiles;
1297 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1298 for (const auto &inProfile : inputProfiles) {
1299 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1300 msdProfiles.appendVector(inProfile->getAudioProfiles());
1301 }
1302 }
1303 AudioProfileVector deviceProfiles;
1304 for (const auto &outProfile : outputProfiles) {
1305 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1306 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1307 }
1308 }
1309 struct audio_config_base bestSinkConfig;
1310 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1311 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1312 &bestSinkConfig);
1313 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001314 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1315 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001316 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001317 }
1318 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1319 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1320 sinkConfig->format = bestSinkConfig.format;
1321 // For encoded streams force direct flag to prevent downstream mixing.
1322 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1323 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1324 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1325 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1326 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1327 sourceConfig->format = bestSinkConfig.format;
1328 // Copy input stream directly without any processing (e.g. resampling).
1329 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1330 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1331 if (hwAvSync) {
1332 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1333 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1334 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1335 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1336 }
1337 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1338 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1339 sinkConfig->config_mask |= config_mask;
1340 sourceConfig->config_mask |= config_mask;
1341 return NO_ERROR;
1342}
1343
François Gaffie11d30102018-11-02 16:09:09 +01001344PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001345{
1346 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001347 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001348 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1349 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1350 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1351 // For now, we just forcefully try with HwAvSync first.
1352 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1353 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1354 getBestMsdAudioProfileFor(
1355 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1356 if (res == NO_ERROR) {
1357 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1358 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1359 }
1360 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1361 " supporting PCM format conversion.", __func__);
1362 return patchBuilder;
1363}
1364
François Gaffie11d30102018-11-02 16:09:09 +01001365status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1366 sp<DeviceDescriptor> device = outputDevice;
1367 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001368 // Use media strategy for unspecified output device. This should only
1369 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1370 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001371 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1372 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1373 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001374 }
François Gaffie11d30102018-11-02 16:09:09 +01001375 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1376 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001377 const struct audio_patch* patch = patchBuilder.patch();
1378 const AudioPatchCollection msdPatches = getMsdPatches();
1379 if (!msdPatches.isEmpty()) {
1380 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1381 "The current MSD prototype only supports one output patch");
1382 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1383 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1384 return NO_ERROR;
1385 }
1386 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1387 }
1388 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1389 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1390 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1391 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001392 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1393 device->toString().c_str(), patch->sources[0].format,
1394 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001395 return status;
1396}
1397
Eric Laurente0720872014-03-11 09:30:41 -07001398audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001399 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001400 audio_format_t format,
1401 audio_channel_mask_t channelMask,
1402 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001403{
1404 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001405 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001407 // 1: the output supporting haptic playback when requesting haptic playback
1408 // 2: the output with the highest number of requested policy flags
1409 // 3: the output with the bit depth the closest to the requested one
1410 // 4: the primary output
1411 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001412
1413 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001414 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001415 }
1416 if (outputs.size() == 1) {
1417 return outputs[0];
1418 }
1419
1420 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001421 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1422 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001423 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1424 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1425 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001426 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1427 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001428
Eric Laurente78b6762018-12-19 16:29:01 -08001429 // Flags which must be present on both the request and the selected output
1430 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1431 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1432
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001433 for (audio_io_handle_t output : outputs) {
1434 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001435 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001436 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1437 continue;
1438 }
jiabin40573322018-11-08 12:08:02 -08001439 // If haptic channel is specified, use the haptic output if present.
1440 // When using haptic output, same audio format and sample rate are required.
1441 if (hapticChannelCount > 0) {
1442 // If haptic channel is specified, use the first output that
1443 // support haptic playback.
1444 if (audio_channel_count_from_out_mask(
1445 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1446 && format == outputDesc->mFormat
1447 && samplingRate == outputDesc->mSamplingRate) {
1448 return output;
1449 }
1450 } else {
1451 // When haptic channel is not specified, skip haptic output.
1452 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1453 continue;
1454 }
1455 }
Eric Laurente78b6762018-12-19 16:29:01 -08001456 if ((kMandatedFlags & flags) !=
1457 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1458 continue;
1459 }
jiabin40573322018-11-08 12:08:02 -08001460
Eric Laurent8838a382014-09-08 16:44:28 -07001461 // if a valid format is specified, skip output if not compatible
1462 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001463 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001464 continue;
1465 }
Eric Laurente6930022016-02-11 10:20:40 -08001466 if (AudioPort::isBetterFormatMatch(
1467 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001468 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001469 bestFormat = outputDesc->mFormat;
1470 }
Eric Laurent8838a382014-09-08 16:44:28 -07001471 }
1472
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001473 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001474 if (commonFlags >= maxCommonFlags) {
1475 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001476 if (format != AUDIO_FORMAT_INVALID
1477 && AudioPort::isBetterFormatMatch(
1478 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001479 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001480 bestFormatForFlags = outputDesc->mFormat;
1481 }
1482 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001483 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001484 maxCommonFlags = commonFlags;
1485 bestFormatForFlags = outputDesc->mFormat;
1486 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001487 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001489 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001490 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001491 }
1492 }
1493 }
1494
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001495 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001496 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001497 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001498 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001499 return outputForFormat;
1500 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001501 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001502 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001503 }
1504
1505 return outputs[0];
1506}
1507
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001509{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001510 ALOGV("%s portId %d", __FUNCTION__, portId);
1511
1512 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1513 if (outputDesc == 0) {
1514 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 return BAD_VALUE;
1516 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001517 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001518
Eric Laurent8fc147b2018-07-22 19:13:55 -07001519 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001520 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001521
Eric Laurent733ce942017-12-07 12:18:25 -08001522 status_t status = outputDesc->start();
1523 if (status != NO_ERROR) {
1524 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001525 }
1526
Eric Laurent97ac8712018-07-27 18:59:02 -07001527 uint32_t delayMs;
1528 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001529
1530 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001531 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001532 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001533 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001534 if (delayMs != 0) {
1535 usleep(delayMs * 1000);
1536 }
1537
1538 return status;
1539}
1540
Eric Laurent97ac8712018-07-27 18:59:02 -07001541status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1542 const sp<TrackClientDescriptor>& client,
1543 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001544{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001545 // cannot start playback of STREAM_TTS if any other output is being used
1546 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001547
1548 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001549 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001550 if (stream == AUDIO_STREAM_TTS) {
1551 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001552 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001553 return INVALID_OPERATION;
1554 } else {
1555 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1556 }
1557 } else {
1558 // some playback other than beacon starts
1559 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1560 }
1561
Eric Laurent77305a62016-07-25 16:39:22 -07001562 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001563 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001564 bool force = !outputDesc->isActive() &&
1565 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001566
François Gaffie11d30102018-11-02 16:09:09 +01001567 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001568 AudioMix *policyMix = NULL;
1569 const char *address = NULL;
1570 if (outputDesc->mPolicyMix != NULL) {
1571 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001572 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001573 address = policyMix->mDeviceAddress.string();
1574 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001575 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001576 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001577 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001578 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001579 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1580 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001581 }
1582
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001583 // requiresMuteCheck is false when we can bypass mute strategy.
1584 // It covers a common case when there is no materially active audio
1585 // and muting would result in unnecessary delay and dropped audio.
1586 const uint32_t outputLatencyMs = outputDesc->latency();
1587 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1588
Eric Laurente552edb2014-03-10 17:42:56 -07001589 // increment usage count for this stream on the requested output:
1590 // NOTE that the usage count is the same for duplicated output and hardware output which is
1591 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001592 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001593
1594 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001595 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1596 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001597 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1598 }
1599 }
Eric Laurente552edb2014-03-10 17:42:56 -07001600
Eric Laurent36829f92017-04-07 19:04:42 -07001601 if (stream == AUDIO_STREAM_MUSIC) {
1602 selectOutputForMusicEffects();
1603 }
1604
François Gaffie11d30102018-11-02 16:09:09 +01001605 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001606 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001607 if (devices.isEmpty()) {
1608 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001609 }
Eric Laurent36829f92017-04-07 19:04:42 -07001610
Eric Laurente552edb2014-03-10 17:42:56 -07001611 routing_strategy strategy = getStrategy(stream);
1612 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001613 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1614 (beaconMuteLatency > 0);
1615 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001616 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001617 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001618 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001619 // An output has a shared device if
1620 // - managed by the same hw module
1621 // - supports the currently selected device
1622 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001623 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001624
Eric Laurent77305a62016-07-25 16:39:22 -07001625 // force a device change if any other output is:
1626 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001627 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001628 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001629 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001630 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001631 // change the device currently selected by the other output.
1632 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001633 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001634 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001635 force = true;
1636 }
1637 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001638 // a notification so that audio focus effect can propagate, or that a mute/unmute
1639 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001640 const uint32_t latencyMs = desc->latency();
1641 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1642
1643 if (shouldWait && isActive && (waitMs < latencyMs)) {
1644 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001645 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001646
1647 // Require mute check if another output is on a shared device
1648 // and currently active to have proper drain and avoid pops.
1649 // Note restoring AudioTracks onto this output needs to invoke
1650 // a volume ramp if there is no mute.
1651 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001652 }
1653 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001654
1655 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001656 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001657
Eric Laurente552edb2014-03-10 17:42:56 -07001658 // apply volume rules for current stream and device if necessary
1659 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001660 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001661 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001662 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001663
1664 // update the outputs if starting an output with a stream that can affect notification
1665 // routing
1666 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001667
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001668 // force reevaluating accessibility routing when ringtone or alarm starts
1669 if (strategy == STRATEGY_SONIFICATION) {
1670 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1671 }
Eric Laurentdc462862016-07-19 12:29:53 -07001672
1673 if (waitMs > muteWaitMs) {
1674 *delayMs = waitMs - muteWaitMs;
1675 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001676
1677 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1678 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1679 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1680 // change occurs after the MixerThread starts and causes a stream volume
1681 // glitch.
1682 //
1683 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001684 }
Eric Laurentdc462862016-07-19 12:29:53 -07001685
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001686 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1687 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1688 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1689 }
1690
Eric Laurent97ac8712018-07-27 18:59:02 -07001691 // Automatically enable the remote submix input when output is started on a re routing mix
1692 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001693 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001694 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1695 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1696 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1697 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001698 "remote-submix",
1699 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001700 }
1701
Eric Laurente552edb2014-03-10 17:42:56 -07001702 return NO_ERROR;
1703}
1704
Eric Laurent8fc147b2018-07-22 19:13:55 -07001705status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001706{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001707 ALOGV("%s portId %d", __FUNCTION__, portId);
1708
1709 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1710 if (outputDesc == 0) {
1711 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001712 return BAD_VALUE;
1713 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001714 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent97ac8712018-07-27 18:59:02 -07001716 ALOGV("stopOutput() output %d, stream %d, session %d",
1717 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001718
Eric Laurent97ac8712018-07-27 18:59:02 -07001719 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001720
Eric Laurent733ce942017-12-07 12:18:25 -08001721 if (status == NO_ERROR ) {
1722 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001723 }
1724 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001725}
1726
Eric Laurent97ac8712018-07-27 18:59:02 -07001727status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1728 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001729{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001730 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001731 audio_stream_type_t stream = client->stream();
1732
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001733 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1734
Eric Laurent592dd7b2018-08-05 18:58:48 -07001735 if (outputDesc->streamActiveCount(stream) > 0) {
1736 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001737 // Automatically disable the remote submix input when output is stopped on a
1738 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001739 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001740 outputDesc->mPolicyMix != NULL &&
1741 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1742 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1743 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1744 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001745 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001746 }
1747 }
1748 bool forceDeviceUpdate = false;
1749 if (client->hasPreferredDevice(true)) {
1750 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1751 forceDeviceUpdate = true;
1752 }
1753
Eric Laurente552edb2014-03-10 17:42:56 -07001754 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001755 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001756
Eric Laurente552edb2014-03-10 17:42:56 -07001757 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001758 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001759 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001760 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001761 // delay the device switch by twice the latency because stopOutput() is executed when
1762 // the track stop() command is received and at that time the audio track buffer can
1763 // still contain data that needs to be drained. The latency only covers the audio HAL
1764 // and kernel buffers. Also the latency does not always include additional delay in the
1765 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001766 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001767
1768 // force restoring the device selection on other active outputs if it differs from the
1769 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001770 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001771 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001772 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001773 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001774 desc->isActive() &&
1775 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001776 (newDevices != desc->devices())) {
1777 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1778 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001779
François Gaffie11d30102018-11-02 16:09:09 +01001780 setOutputDevices(desc, newDevices2, force, delayMs);
1781
Eric Laurent57de36c2016-09-28 16:59:11 -07001782 // re-apply device specific volume if not done by setOutputDevice()
1783 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001784 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001785 }
Eric Laurente552edb2014-03-10 17:42:56 -07001786 }
1787 }
1788 // update the outputs if stopping one with a stream that can affect notification routing
1789 handleNotificationRoutingForStream(stream);
1790 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001791
1792 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1793 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1794 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1795 }
1796
Eric Laurent36829f92017-04-07 19:04:42 -07001797 if (stream == AUDIO_STREAM_MUSIC) {
1798 selectOutputForMusicEffects();
1799 }
Eric Laurente552edb2014-03-10 17:42:56 -07001800 return NO_ERROR;
1801 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001802 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001803 return INVALID_OPERATION;
1804 }
1805}
1806
Eric Laurent8fc147b2018-07-22 19:13:55 -07001807void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001808{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001809 ALOGV("%s portId %d", __FUNCTION__, portId);
1810
1811 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1812 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001813 // If an output descriptor is closed due to a device routing change,
1814 // then there are race conditions with releaseOutput from tracks
1815 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1816 // destroyed shortly thereafter.
1817 //
1818 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001819 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001820 return;
1821 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001822
1823 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001824
Eric Laurent8fc147b2018-07-22 19:13:55 -07001825 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1826 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001827 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001828 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001829 return;
1830 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001831 if (--outputDesc->mDirectOpenCount == 0) {
1832 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001833 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001834 }
1835 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001836 // stopOutput() needs to be successfully called before releaseOutput()
1837 // otherwise there may be inaccurate stream reference counts.
1838 // This is checked in outputDesc->removeClient below.
1839 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001840}
1841
Eric Laurentcaf7f482014-11-25 17:50:47 -08001842status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1843 audio_io_handle_t *input,
1844 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001845 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001846 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001847 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001848 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001849 input_type_t *inputType,
1850 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001851{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001852 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001853 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001854 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001855
Eric Laurentad2e7b92017-09-14 20:06:42 -07001856 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001857 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001858 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001859 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001860 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001861 sp<AudioInputDescriptor> inputDesc;
1862 sp<RecordClientDescriptor> clientDesc;
1863 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001864 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001865
1866 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1867 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1868 return INVALID_OPERATION;
1869 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001870
Francois Gaffie716e1432019-01-14 16:58:59 +01001871 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1872 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001873 }
1874
Paul McLean466dc8e2015-04-17 13:15:36 -06001875 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001876 sp<DeviceDescriptor> explicitRoutingDevice =
1877 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001878
Eric Laurentad2e7b92017-09-14 20:06:42 -07001879 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1880 // possible
1881 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1882 *input != AUDIO_IO_HANDLE_NONE) {
1883 ssize_t index = mInputs.indexOfKey(*input);
1884 if (index < 0) {
1885 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1886 status = BAD_VALUE;
1887 goto error;
1888 }
1889 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001890 RecordClientVector clients = inputDesc->getClientsForSession(session);
1891 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001892 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1893 status = BAD_VALUE;
1894 goto error;
1895 }
1896 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1897 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001898 // corresponds to a new client and is only permitted from the same UID.
1899 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001900 if (clients.size() > 1) {
1901 for (const auto& client : clients) {
1902 // The client map is ordered by key values (portId) and portIds are allocated
1903 // incrementaly. So the first client in this list is the one opened by audio flinger
1904 // when the mmap stream is created and should be ignored as it does not correspond
1905 // to an actual client
1906 if (client == *clients.cbegin()) {
1907 continue;
1908 }
1909 if (uid != client->uid() && !client->isSilenced()) {
1910 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1911 uid, client->portId(), client->uid());
1912 status = INVALID_OPERATION;
1913 goto error;
1914 }
Eric Laurent331679c2018-04-16 17:03:16 -07001915 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001916 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001917 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001918 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001919
Eric Laurent8f42ea12018-08-08 09:08:25 -07001920 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001921 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001922 }
1923
1924 *input = AUDIO_IO_HANDLE_NONE;
1925 *inputType = API_INPUT_INVALID;
1926
Francois Gaffie716e1432019-01-14 16:58:59 +01001927 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001928
Francois Gaffie716e1432019-01-14 16:58:59 +01001929 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1930 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1931 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001932 if (status != NO_ERROR) {
1933 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001934 }
1935 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001936 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001937 String8(attr->tags + strlen("addr=")),
1938 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001939 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001940 if (explicitRoutingDevice != nullptr) {
1941 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001942 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001943 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001944 }
François Gaffie11d30102018-11-02 16:09:09 +01001945 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001946 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001947 status = BAD_VALUE;
1948 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001949 }
François Gaffie11d30102018-11-02 16:09:09 +01001950 if (policyMix != nullptr) {
1951 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1952 // there is an external policy, but this input is attached to a mix of recorders,
1953 // meaning it receives audio injected into the framework, so the recorder doesn't
1954 // know about it and is therefore considered "legacy"
1955 *inputType = API_INPUT_LEGACY;
1956 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001957 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1958 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001959 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001960 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001961 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001962 } else {
1963 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001964 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001965
Eric Laurent599c7582015-12-07 18:05:55 -08001966 }
1967
Francois Gaffie716e1432019-01-14 16:58:59 +01001968 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001969 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001970 policyMix);
1971 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001972 status = INVALID_OPERATION;
1973 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001974 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001975
Eric Laurent8f42ea12018-08-08 09:08:25 -07001976exit:
1977
François Gaffie11d30102018-11-02 16:09:09 +01001978 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1979 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001980
Francois Gaffie716e1432019-01-14 16:58:59 +01001981 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001982 mSoundTriggerSessions.indexOfKey(session) > 0;
1983 *portId = AudioPort::getNextUniqueId();
1984
François Gaffie11d30102018-11-02 16:09:09 +01001985 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001986 requestedDeviceId, attributes.source, flags,
1987 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001988 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001989 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001990
1991 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1992 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001993
Eric Laurent599c7582015-12-07 18:05:55 -08001994 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001995
1996error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001997 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001998}
1999
2000
François Gaffie11d30102018-11-02 16:09:09 +01002001audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002002 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08002003 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08002004 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002005 audio_input_flags_t flags,
2006 AudioMix *policyMix)
2007{
2008 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2009 audio_source_t halInputSource = inputSource;
2010 bool isSoundTrigger = false;
2011
2012 if (inputSource == AUDIO_SOURCE_HOTWORD) {
2013 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2014 if (index >= 0) {
2015 input = mSoundTriggerSessions.valueFor(session);
2016 isSoundTrigger = true;
2017 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2018 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2019 } else {
2020 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002021 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002022 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002023 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002024 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002025 }
2026
Andy Hungf129b032015-04-07 13:45:50 -07002027 // find a compatible input profile (not necessarily identical in parameters)
2028 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002029 // sampling rate and flags may be updated by getInputProfile
2030 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2031 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002032 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002033 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002034 audio_input_flags_t profileFlags = flags;
2035 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002036 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002037 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002038 profileFlags);
2039 if (profile != 0) {
2040 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002041 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2042 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002043 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2044 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2045 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002046 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2047 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2048 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002049 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002050 }
Eric Laurente552edb2014-03-10 17:42:56 -07002051 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002052 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002053 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002054 if (samplingRate == 0) {
2055 samplingRate = profileSamplingRate;
2056 }
Eric Laurente552edb2014-03-10 17:42:56 -07002057
Eric Laurent322b4d22015-04-03 15:57:54 -07002058 if (profile->getModuleHandle() == 0) {
2059 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002060 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002061 }
2062
Eric Laurent3974e3b2017-12-07 17:58:43 -08002063 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002064 for (size_t i = 0; i < mInputs.size(); ) {
2065 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2066 if (desc->mProfile != profile) {
2067 continue;
2068 }
2069 // if sound trigger, reuse input if used by other sound trigger on same session
2070 // else
2071 // reuse input if active client app is not in IDLE state
2072 //
2073 RecordClientVector clients = desc->clientsList();
2074 bool doClose = false;
2075 for (const auto& client : clients) {
2076 if (isSoundTrigger != client->isSoundTrigger()) {
2077 continue;
2078 }
2079 if (client->isSoundTrigger()) {
2080 if (session == client->session()) {
2081 return desc->mIoHandle;
2082 }
2083 continue;
2084 }
2085 if (client->active() && client->appState() != APP_STATE_IDLE) {
2086 return desc->mIoHandle;
2087 }
2088 doClose = true;
2089 }
2090 if (doClose) {
2091 closeInput(desc->mIoHandle);
2092 } else {
2093 i++;
2094 }
2095 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002096 }
2097
Eric Laurentfe231122017-11-17 17:48:06 -08002098 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002099
Eric Laurentfe231122017-11-17 17:48:06 -08002100 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2101 lConfig.sample_rate = profileSamplingRate;
2102 lConfig.channel_mask = profileChannelMask;
2103 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002104
François Gaffie11d30102018-11-02 16:09:09 +01002105 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002106
2107 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002108 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002109 (profileSamplingRate != lConfig.sample_rate) ||
2110 !audio_formats_match(profileFormat, lConfig.format) ||
2111 (profileChannelMask != lConfig.channel_mask)) {
2112 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002113 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002114 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002115 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002116 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002117 }
Eric Laurent599c7582015-12-07 18:05:55 -08002118 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002119 }
2120
Eric Laurentc722f302014-12-10 11:21:49 -08002121 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002122
Eric Laurent599c7582015-12-07 18:05:55 -08002123 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002124 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002125
Eric Laurent599c7582015-12-07 18:05:55 -08002126 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002127}
2128
Eric Laurent4eb58f12018-12-07 16:41:02 -08002129status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002130{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002131 ALOGV("%s portId %d", __FUNCTION__, portId);
2132
2133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2134 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002135 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136 return BAD_VALUE;
2137 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002139 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 if (client->active()) {
2141 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2142 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002143 }
2144
Eric Laurent8f42ea12018-08-08 09:08:25 -07002145 audio_session_t session = client->session();
2146
Eric Laurent4eb58f12018-12-07 16:41:02 -08002147 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002148
Eric Laurent4eb58f12018-12-07 16:41:02 -08002149 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002150
Eric Laurent4eb58f12018-12-07 16:41:02 -08002151 status_t status = inputDesc->start();
2152 if (status != NO_ERROR) {
2153 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002154 }
Eric Laurente552edb2014-03-10 17:42:56 -07002155
Eric Laurent4eb58f12018-12-07 16:41:02 -08002156 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002157 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002159
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 // indicate active capture to sound trigger service if starting capture from a mic on
2161 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002162 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002163 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002164
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 if (inputDesc->activeCount() == 1) {
2166 // if input maps to a dynamic policy with an activity listener, notify of state change
2167 if ((inputDesc->mPolicyMix != NULL)
2168 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2169 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2170 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002171 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002172
François Gaffie11d30102018-11-02 16:09:09 +01002173 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2174 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002175 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2176 SoundTrigger::setCaptureState(true);
2177 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002178
Eric Laurent8f42ea12018-08-08 09:08:25 -07002179 // automatically enable the remote submix output when input is started if not
2180 // used by a policy mix of type MIX_TYPE_RECORDERS
2181 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002182 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002183 String8 address = String8("");
2184 if (inputDesc->mPolicyMix == NULL) {
2185 address = String8("0");
2186 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2187 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002188 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002189 if (address != "") {
2190 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2191 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002192 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002193 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002194 }
Eric Laurente552edb2014-03-10 17:42:56 -07002195 }
2196
Eric Laurent8f42ea12018-08-08 09:08:25 -07002197 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002198
Eric Laurente552edb2014-03-10 17:42:56 -07002199 return NO_ERROR;
2200}
2201
Eric Laurent8fc147b2018-07-22 19:13:55 -07002202status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002203{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204 ALOGV("%s portId %d", __FUNCTION__, portId);
2205
2206 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2207 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002209 return BAD_VALUE;
2210 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002211 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213 if (!client->active()) {
2214 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002215 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002216 }
2217
Eric Laurent8f42ea12018-08-08 09:08:25 -07002218 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002219
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220 inputDesc->stop();
2221 if (inputDesc->isActive()) {
2222 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2223 } else {
2224 // if input maps to a dynamic policy with an activity listener, notify of state change
2225 if ((inputDesc->mPolicyMix != NULL)
2226 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2227 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2228 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002229 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230
2231 // automatically disable the remote submix output when input is stopped if not
2232 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002233 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002234 String8 address = String8("");
2235 if (inputDesc->mPolicyMix == NULL) {
2236 address = String8("0");
2237 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2238 address = inputDesc->mPolicyMix->mDeviceAddress;
2239 }
2240 if (address != "") {
2241 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2242 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002243 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002244 }
2245 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002246 resetInputDevice(input);
2247
2248 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2249 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002250 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2251 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002252 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2253 SoundTrigger::setCaptureState(false);
2254 }
2255 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002256 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002257 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002258}
2259
Eric Laurent8fc147b2018-07-22 19:13:55 -07002260void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002261{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002262 ALOGV("%s portId %d", __FUNCTION__, portId);
2263
2264 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2265 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002266 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002267 return;
2268 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002269 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002270 audio_io_handle_t input = inputDesc->mIoHandle;
2271
Eric Laurent8f42ea12018-08-08 09:08:25 -07002272 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002273
Andy Hung39efb7a2018-09-26 15:39:28 -07002274 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002275
Andy Hung39efb7a2018-09-26 15:39:28 -07002276 if (inputDesc->getClientCount() > 0) {
2277 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002278 return;
2279 }
2280
Eric Laurent05b90f82014-08-27 15:32:29 -07002281 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002282 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002283 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002284}
2285
Eric Laurent8f42ea12018-08-08 09:08:25 -07002286void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002288 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002289
2290 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002291 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002292 }
2293}
2294
Eric Laurent8f42ea12018-08-08 09:08:25 -07002295void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2296{
2297 stopInput(portId);
2298 releaseInput(portId);
2299}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002300
Eric Laurentd4692962014-05-05 18:13:44 -07002301void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002302 bool patchRemoved = false;
2303
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002304 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002305 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002306 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002307 if (patch_index >= 0) {
2308 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002309 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002310 mAudioPatches.removeItemsAt(patch_index);
2311 patchRemoved = true;
2312 }
Eric Laurentfe231122017-11-17 17:48:06 -08002313 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002314 }
2315 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002316 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002317 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002318
2319 if (patchRemoved) {
2320 mpClientInterface->onAudioPatchListUpdate();
2321 }
Eric Laurentd4692962014-05-05 18:13:44 -07002322}
2323
Eric Laurente0720872014-03-11 09:30:41 -07002324void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002325 int indexMin,
2326 int indexMax)
2327{
2328 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002329 if (indexMin < 0 || indexMax < 0) {
2330 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2331 return;
2332 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01002333 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002334
2335 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002336 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2337 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002338 continue;
2339 }
2340 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002341 }
Eric Laurente552edb2014-03-10 17:42:56 -07002342}
2343
Eric Laurente0720872014-03-11 09:30:41 -07002344status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002345 int index,
2346 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002347{
2348
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002349 // VOICE_CALL and BLUETOOTH_SCO stream have minVolumeIndex > 0 but
2350 // can be muted directly by an app that has MODIFY_PHONE_STATE permission.
Nadav Bar7c605f62017-12-25 00:01:52 +02002351 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002352 !((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
2353 index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002354 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002355 return BAD_VALUE;
2356 }
2357 if (!audio_is_output_device(device)) {
2358 return BAD_VALUE;
2359 }
2360
2361 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002362 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002363
Eric Laurent1fd372e2016-04-06 14:23:53 -07002364 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002365 stream, device, index);
2366
Eric Laurent28d09f02016-03-08 10:43:05 -08002367 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002368 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2369 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002370 continue;
2371 }
2372 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2373 }
Eric Laurente552edb2014-03-10 17:42:56 -07002374
Eric Laurent1fd372e2016-04-06 14:23:53 -07002375 // update volume on all outputs and streams matching the following:
2376 // - The requested stream (or a stream matching for volume control) is active on the output
2377 // - The device (or devices) selected by the strategy corresponding to this stream includes
2378 // the requested device
2379 // - For non default requested device, currently selected device on the output is either the
2380 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002381 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2382 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002383 status_t status = NO_ERROR;
2384 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002385 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002386 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002387 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002388 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002389 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002390 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002391 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002392 continue;
2393 }
Eric Laurent794fde22016-03-11 09:50:45 -08002394 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002395 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2396 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002397 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2398 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002399 continue;
2400 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002401 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002402 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002403 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002404 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002405 } else {
2406 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002407 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002408 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002409 // rescale index before applying to curStream as ranges may be different for
2410 // stream and curStream
2411 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002412 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002413 //FIXME: workaround for truncated touch sounds
2414 // delayed volume change for system stream to be removed when the problem is
2415 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002416 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002417 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002418 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002419 if (volStatus != NO_ERROR) {
2420 status = volStatus;
2421 }
2422 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002423 }
Eric Laurente552edb2014-03-10 17:42:56 -07002424 }
2425 return status;
2426}
2427
Eric Laurente0720872014-03-11 09:30:41 -07002428status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002429 int *index,
2430 audio_devices_t device)
2431{
2432 if (index == NULL) {
2433 return BAD_VALUE;
2434 }
2435 if (!audio_is_output_device(device)) {
2436 return BAD_VALUE;
2437 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002438 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002439 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002440 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002441 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2442 }
François Gaffiedfd74092015-03-19 12:10:59 +01002443 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002444
François Gaffied1ab2bd2015-12-02 18:20:06 +01002445 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002446 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2447 return NO_ERROR;
2448}
2449
Eric Laurent36829f92017-04-07 19:04:42 -07002450audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002451{
2452 // select one output among several suitable for global effects.
2453 // The priority is as follows:
2454 // 1: An offloaded output. If the effect ends up not being offloadable,
2455 // AudioFlinger will invalidate the track and the offloaded output
2456 // will be closed causing the effect to be moved to a PCM output.
2457 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002458 // 3: The primary output
2459 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002460
Eric Laurent3b73df72014-03-11 09:06:29 -07002461 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002462 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2463 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent36829f92017-04-07 19:04:42 -07002465 if (outputs.size() == 0) {
2466 return AUDIO_IO_HANDLE_NONE;
2467 }
Eric Laurente552edb2014-03-10 17:42:56 -07002468
Eric Laurent36829f92017-04-07 19:04:42 -07002469 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2470 bool activeOnly = true;
2471
2472 while (output == AUDIO_IO_HANDLE_NONE) {
2473 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2474 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2475 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2476
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002477 for (audio_io_handle_t output : outputs) {
2478 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002479 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2480 continue;
2481 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002482 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2483 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002484 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002485 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002486 }
2487 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002488 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002489 }
2490 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002491 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002492 }
2493 }
2494 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2495 output = outputOffloaded;
2496 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2497 output = outputDeepBuffer;
2498 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2499 output = outputPrimary;
2500 } else {
2501 output = outputs[0];
2502 }
2503 activeOnly = false;
2504 }
2505
2506 if (output != mMusicEffectOutput) {
2507 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2508 mMusicEffectOutput = output;
2509 }
2510
2511 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002512 return output;
2513}
2514
Eric Laurent36829f92017-04-07 19:04:42 -07002515audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2516{
2517 return selectOutputForMusicEffects();
2518}
2519
Eric Laurente0720872014-03-11 09:30:41 -07002520status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002521 audio_io_handle_t io,
2522 uint32_t strategy,
2523 int session,
2524 int id)
2525{
2526 ssize_t index = mOutputs.indexOfKey(io);
2527 if (index < 0) {
2528 index = mInputs.indexOfKey(io);
2529 if (index < 0) {
2530 ALOGW("registerEffect() unknown io %d", io);
2531 return INVALID_OPERATION;
2532 }
2533 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002534 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002535}
2536
Eric Laurentc241b0d2018-11-28 09:08:49 -08002537status_t AudioPolicyManager::unregisterEffect(int id)
2538{
2539 if (mEffects.getEffect(id) == nullptr) {
2540 return INVALID_OPERATION;
2541 }
2542
2543 if (mEffects.isEffectEnabled(id)) {
2544 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2545 setEffectEnabled(id, false);
2546 }
2547 return mEffects.unregisterEffect(id);
2548}
2549
2550status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2551{
2552 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2553 if (effect == nullptr) {
2554 return INVALID_OPERATION;
2555 }
2556
2557 status_t status = mEffects.setEffectEnabled(id, enabled);
2558 if (status == NO_ERROR) {
2559 mInputs.trackEffectEnabled(effect, enabled);
2560 }
2561 return status;
2562}
2563
Eric Laurentc75307b2015-03-17 15:29:32 -07002564bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2565{
Eric Laurent28d09f02016-03-08 10:43:05 -08002566 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002567 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2568 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002569 continue;
2570 }
2571 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2572 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002573 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002574}
2575
2576bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2577{
2578 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2579}
2580
Eric Laurente0720872014-03-11 09:30:41 -07002581bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002582{
2583 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002584 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002585 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002586 return true;
2587 }
2588 }
2589 return false;
2590}
2591
Eric Laurent275e8e92014-11-30 15:14:47 -08002592// Register a list of custom mixes with their attributes and format.
2593// When a mix is registered, corresponding input and output profiles are
2594// added to the remote submix hw module. The profile contains only the
2595// parameters (sampling rate, format...) specified by the mix.
2596// The corresponding input remote submix device is also connected.
2597//
2598// When a remote submix device is connected, the address is checked to select the
2599// appropriate profile and the corresponding input or output stream is opened.
2600//
2601// When capture starts, getInputForAttr() will:
2602// - 1 look for a mix matching the address passed in attribtutes tags if any
2603// - 2 if none found, getDeviceForInputSource() will:
2604// - 2.1 look for a mix matching the attributes source
2605// - 2.2 if none found, default to device selection by policy rules
2606// At this time, the corresponding output remote submix device is also connected
2607// and active playback use cases can be transferred to this mix if needed when reconnecting
2608// after AudioTracks are invalidated
2609//
2610// When playback starts, getOutputForAttr() will:
2611// - 1 look for a mix matching the address passed in attribtutes tags if any
2612// - 2 if none found, look for a mix matching the attributes usage
2613// - 3 if none found, default to device and output selection by policy rules.
2614
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002615status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002616{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002617 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2618 status_t res = NO_ERROR;
2619
2620 sp<HwModule> rSubmixModule;
2621 // examine each mix's route type
2622 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002623 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002624 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002627 break;
2628 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002629 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002631 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002632 rSubmixModule = mHwModules.getModuleFromName(
2633 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2634 if (rSubmixModule == 0) {
2635 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2636 i);
2637 res = INVALID_OPERATION;
2638 break;
2639 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002640 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002641
Eric Laurent97ac8712018-07-27 18:59:02 -07002642 String8 address = mix.mDeviceAddress;
2643 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2644 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2645 } else {
2646 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2647 }
François Gaffie036e1e92015-03-19 10:16:24 +01002648
Eric Laurent97ac8712018-07-27 18:59:02 -07002649 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002650 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002651 res = INVALID_OPERATION;
2652 break;
2653 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002654 audio_config_t outputConfig = mix.mFormat;
2655 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002656 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2657 // stereo and let audio flinger do the channel conversion if needed.
2658 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2659 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2660 rSubmixModule->addOutputProfile(address, &outputConfig,
2661 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2662 rSubmixModule->addInputProfile(address, &inputConfig,
2663 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002664
Eric Laurent97ac8712018-07-27 18:59:02 -07002665 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002666 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2667 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002668 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 } else {
2670 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2671 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002672 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002673 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2675 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002676 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002677 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002678 i, mixes.size(), type, address.string());
2679
2680 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2681 mix.mDeviceType, mix.mDeviceAddress,
2682 String8(), AUDIO_FORMAT_DEFAULT);
2683 if (device == nullptr) {
2684 res = INVALID_OPERATION;
2685 break;
2686 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002687
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002688 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002689 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002691
2692 if (desc->supportedDevices().contains(device)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002693 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002694 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002695 } else {
2696 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002697 }
2698 break;
2699 }
2700 }
2701
2702 if (res != NO_ERROR) {
2703 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002704 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002705 res = INVALID_OPERATION;
2706 break;
2707 } else if (!foundOutput) {
2708 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002709 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002710 res = INVALID_OPERATION;
2711 break;
2712 }
Eric Laurentc722f302014-12-10 11:21:49 -08002713 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002714 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002715 if (res != NO_ERROR) {
2716 unregisterPolicyMixes(mixes);
2717 }
2718 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002719}
2720
2721status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2722{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002723 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002724 status_t res = NO_ERROR;
2725 sp<HwModule> rSubmixModule;
2726 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002727 for (const auto& mix : mixes) {
2728 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002729
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002730 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002731 rSubmixModule = mHwModules.getModuleFromName(
2732 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2733 if (rSubmixModule == 0) {
2734 res = INVALID_OPERATION;
2735 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002736 }
2737 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002738
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002739 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002740
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002741 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2742 res = INVALID_OPERATION;
2743 continue;
2744 }
2745
2746 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2747 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2748 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2749 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002750 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002751 }
2752 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2753 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2754 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2755 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002756 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002757 }
2758 rSubmixModule->removeOutputProfile(address);
2759 rSubmixModule->removeInputProfile(address);
2760
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002761 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2762 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002763 res = INVALID_OPERATION;
2764 continue;
2765 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002766 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002767 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002768 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002769}
2770
Mikhail Naganov100f0122018-11-29 11:22:16 -08002771void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2772{
2773 size_t i = 0;
2774 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2775 for (const auto& fmt : mManualSurroundFormats) {
2776 if (i++ != 0) dst->append(", ");
2777 std::string sfmt;
2778 FormatConverter::toString(fmt, sfmt);
2779 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2780 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2781 }
2782}
2783
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002784status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2785 const Vector<AudioDeviceTypeAddr>& devices) {
2786 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2787 // uid/device affinity is only for output devices
2788 for (size_t i = 0; i < devices.size(); i++) {
2789 if (!audio_is_output_device(devices[i].mType)) {
2790 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2791 devices[i].mType);
2792 return BAD_VALUE;
2793 }
2794 }
2795 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2796 if (res == NO_ERROR) {
2797 // reevaluate outputs for all given devices
2798 for (size_t i = 0; i < devices.size(); i++) {
2799 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002800 devices[i].mType, devices[i].mAddress, String8(),
2801 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002802 SortedVector<audio_io_handle_t> outputs;
2803 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002804 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002805 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2806 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2807 return INVALID_OPERATION;
2808 }
2809 }
2810 }
2811 return res;
2812}
2813
2814status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2815 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2816 Vector<AudioDeviceTypeAddr> devices;
2817 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2818 if (res == NO_ERROR) {
2819 // reevaluate outputs for all found devices
2820 for (size_t i = 0; i < devices.size(); i++) {
2821 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002822 devices[i].mType, devices[i].mAddress, String8(),
2823 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002824 SortedVector<audio_io_handle_t> outputs;
2825 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002826 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002827 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2828 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2829 return INVALID_OPERATION;
2830 }
2831 }
2832 }
2833
2834 return res;
2835}
2836
Andy Hungc29d82b2018-10-05 12:23:17 -07002837void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002838{
Andy Hungc29d82b2018-10-05 12:23:17 -07002839 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2840 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002841 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002842 std::string stateLiteral;
2843 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002844 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002845 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2846 "communications", "media", "record", "dock", "system",
2847 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2848 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2849 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002850 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2851 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2852 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2853 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2854 dst->append(" (MANUAL: ");
2855 dumpManualSurroundFormats(dst);
2856 dst->append(")");
2857 }
2858 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002859 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002860 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2861 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2862 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2863 mAvailableOutputDevices.dump(dst, String8("Available output"));
2864 mAvailableInputDevices.dump(dst, String8("Available input"));
2865 mHwModulesAll.dump(dst);
2866 mOutputs.dump(dst);
2867 mInputs.dump(dst);
2868 mVolumeCurves->dump(dst);
2869 mEffects.dump(dst);
2870 mAudioPatches.dump(dst);
2871 mPolicyMixes.dump(dst);
2872 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002873}
2874
2875status_t AudioPolicyManager::dump(int fd)
2876{
2877 String8 result;
2878 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002879 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002880 return NO_ERROR;
2881}
2882
2883// This function checks for the parameters which can be offloaded.
2884// This can be enhanced depending on the capability of the DSP and policy
2885// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002886bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002887{
2888 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002889 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002890 offloadInfo.sample_rate, offloadInfo.channel_mask,
2891 offloadInfo.format,
2892 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2893 offloadInfo.has_video);
2894
Andy Hung2ddee192015-12-18 17:34:44 -08002895 if (mMasterMono) {
2896 return false; // no offloading if mono is set.
2897 }
2898
Eric Laurente552edb2014-03-10 17:42:56 -07002899 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002900 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2901 ALOGV("offload disabled by audio.offload.disable");
2902 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002903 }
2904
2905 // Check if stream type is music, then only allow offload as of now.
2906 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2907 {
2908 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2909 return false;
2910 }
2911
2912 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002913 const bool allowOffloadWithVideo =
2914 property_get_bool("audio.offload.video", false /* default_value */);
2915 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002916 ALOGV("isOffloadSupported: has_video == true, returning false");
2917 return false;
2918 }
2919
2920 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002921 const int min_duration_secs = property_get_int32(
2922 "audio.offload.min.duration.secs", -1 /* default_value */);
2923 if (min_duration_secs >= 0) {
2924 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2925 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2926 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002927 return false;
2928 }
2929 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2930 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2931 return false;
2932 }
2933
2934 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2935 // creating an offloaded track and tearing it down immediately after start when audioflinger
2936 // detects there is an active non offloadable effect.
2937 // FIXME: We should check the audio session here but we do not have it in this context.
2938 // This may prevent offloading in rare situations where effects are left active by apps
2939 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002940 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002941 return false;
2942 }
2943
2944 // See if there is a profile to support this.
2945 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002946 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002947 offloadInfo.sample_rate,
2948 offloadInfo.format,
2949 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002950 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2951 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002952 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2953 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002954}
2955
Michael Chana94fbb22018-04-24 14:31:19 +10002956bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2957 const audio_attributes_t& attributes) {
2958 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2959 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002960 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002961 config.sample_rate,
2962 config.format,
2963 config.channel_mask,
2964 output_flags,
2965 true /* directOnly */);
2966 ALOGV("%s() profile %sfound with name: %s, "
2967 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2968 __FUNCTION__, profile != 0 ? "" : "NOT ",
2969 (profile != 0 ? profile->getTagName().string() : "null"),
2970 config.sample_rate, config.format, config.channel_mask, output_flags);
2971 return (profile != 0);
2972}
2973
Eric Laurent6a94d692014-05-20 11:18:06 -07002974status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2975 audio_port_type_t type,
2976 unsigned int *num_ports,
2977 struct audio_port *ports,
2978 unsigned int *generation)
2979{
2980 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2981 generation == NULL) {
2982 return BAD_VALUE;
2983 }
2984 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2985 if (ports == NULL) {
2986 *num_ports = 0;
2987 }
2988
2989 size_t portsWritten = 0;
2990 size_t portsMax = *num_ports;
2991 *num_ports = 0;
2992 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002993 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2994 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002996 for (const auto& dev : mAvailableOutputDevices) {
2997 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002998 continue;
2999 }
3000 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003001 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003002 }
3003 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 }
3006 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003007 for (const auto& dev : mAvailableInputDevices) {
3008 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003009 continue;
3010 }
3011 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003012 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003013 }
3014 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003015 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003016 }
3017 }
3018 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3019 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3020 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3021 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3022 }
3023 *num_ports += mInputs.size();
3024 }
3025 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003026 size_t numOutputs = 0;
3027 for (size_t i = 0; i < mOutputs.size(); i++) {
3028 if (!mOutputs[i]->isDuplicated()) {
3029 numOutputs++;
3030 if (portsWritten < portsMax) {
3031 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3032 }
3033 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 }
Eric Laurent84c70242014-06-23 08:46:27 -07003035 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003036 }
3037 }
3038 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003039 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 return NO_ERROR;
3041}
3042
Eric Laurent99fcae42018-05-17 16:59:18 -07003043status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003044{
Eric Laurent99fcae42018-05-17 16:59:18 -07003045 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3046 return BAD_VALUE;
3047 }
3048 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3049 if (dev != 0) {
3050 dev->toAudioPort(port);
3051 return NO_ERROR;
3052 }
3053 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3054 if (dev != 0) {
3055 dev->toAudioPort(port);
3056 return NO_ERROR;
3057 }
3058 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3059 if (out != 0) {
3060 out->toAudioPort(port);
3061 return NO_ERROR;
3062 }
3063 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3064 if (in != 0) {
3065 in->toAudioPort(port);
3066 return NO_ERROR;
3067 }
3068 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003069}
3070
Eric Laurent6a94d692014-05-20 11:18:06 -07003071status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3072 audio_patch_handle_t *handle,
3073 uid_t uid)
3074{
3075 ALOGV("createAudioPatch()");
3076
3077 if (handle == NULL || patch == NULL) {
3078 return BAD_VALUE;
3079 }
3080 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3081
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003082 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003083 return BAD_VALUE;
3084 }
3085 // only one source per audio patch supported for now
3086 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003087 return INVALID_OPERATION;
3088 }
Eric Laurent874c42872014-08-08 15:13:39 -07003089
3090 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 return INVALID_OPERATION;
3092 }
Eric Laurent874c42872014-08-08 15:13:39 -07003093 for (size_t i = 0; i < patch->num_sinks; i++) {
3094 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3095 return INVALID_OPERATION;
3096 }
3097 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003098
3099 sp<AudioPatch> patchDesc;
3100 ssize_t index = mAudioPatches.indexOfKey(*handle);
3101
Eric Laurent6a94d692014-05-20 11:18:06 -07003102 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3103 patch->sources[0].role,
3104 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003105#if LOG_NDEBUG == 0
3106 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003107 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003108 patch->sinks[i].role,
3109 patch->sinks[i].type);
3110 }
3111#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003112
3113 if (index >= 0) {
3114 patchDesc = mAudioPatches.valueAt(index);
3115 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3116 mUidCached, patchDesc->mUid, uid);
3117 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3118 return INVALID_OPERATION;
3119 }
3120 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003121 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 }
3123
3124 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003125 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003126 if (outputDesc == NULL) {
3127 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3128 return BAD_VALUE;
3129 }
Eric Laurent84c70242014-06-23 08:46:27 -07003130 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3131 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 if (patchDesc != 0) {
3133 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3134 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3135 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3136 return BAD_VALUE;
3137 }
3138 }
Eric Laurent874c42872014-08-08 15:13:39 -07003139 DeviceVector devices;
3140 for (size_t i = 0; i < patch->num_sinks; i++) {
3141 // Only support mix to devices connection
3142 // TODO add support for mix to mix connection
3143 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3144 ALOGV("createAudioPatch() source mix but sink is not a device");
3145 return INVALID_OPERATION;
3146 }
3147 sp<DeviceDescriptor> devDesc =
3148 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3149 if (devDesc == 0) {
3150 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3151 return BAD_VALUE;
3152 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003153
François Gaffie11d30102018-11-02 16:09:09 +01003154 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003155 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003156 NULL, // updatedSamplingRate
3157 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003158 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003159 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003160 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003161 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003162 ALOGV("createAudioPatch() profile not supported for device %08x",
3163 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003164 return INVALID_OPERATION;
3165 }
3166 devices.add(devDesc);
3167 }
3168 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 return INVALID_OPERATION;
3170 }
Eric Laurent874c42872014-08-08 15:13:39 -07003171
Eric Laurent6a94d692014-05-20 11:18:06 -07003172 // TODO: reconfigure output format and channels here
3173 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003174 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003175 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 index = mAudioPatches.indexOfKey(*handle);
3177 if (index >= 0) {
3178 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3179 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3180 }
3181 patchDesc = mAudioPatches.valueAt(index);
3182 patchDesc->mUid = uid;
3183 ALOGV("createAudioPatch() success");
3184 } else {
3185 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3186 return INVALID_OPERATION;
3187 }
3188 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3189 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3190 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003191 // only one sink supported when connecting an input device to a mix
3192 if (patch->num_sinks > 1) {
3193 return INVALID_OPERATION;
3194 }
François Gaffie53615e22015-03-19 09:24:12 +01003195 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 if (inputDesc == NULL) {
3197 return BAD_VALUE;
3198 }
3199 if (patchDesc != 0) {
3200 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3201 return BAD_VALUE;
3202 }
3203 }
François Gaffie11d30102018-11-02 16:09:09 +01003204 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003205 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003206 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003207 return BAD_VALUE;
3208 }
3209
François Gaffie11d30102018-11-02 16:09:09 +01003210 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003211 patch->sinks[0].sample_rate,
3212 NULL, /*updatedSampleRate*/
3213 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003214 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003215 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003216 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003217 // FIXME for the parameter type,
3218 // and the NONE
3219 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003220 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003221 return INVALID_OPERATION;
3222 }
3223 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003224 ALOGV("%s() setting device %s on output %d", __func__,
3225 device->toString().c_str(), inputDesc->mIoHandle);
3226 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003227 index = mAudioPatches.indexOfKey(*handle);
3228 if (index >= 0) {
3229 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3230 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3231 }
3232 patchDesc = mAudioPatches.valueAt(index);
3233 patchDesc->mUid = uid;
3234 ALOGV("createAudioPatch() success");
3235 } else {
3236 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3237 return INVALID_OPERATION;
3238 }
3239 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3240 // device to device connection
3241 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003242 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003243 return BAD_VALUE;
3244 }
3245 }
François Gaffie11d30102018-11-02 16:09:09 +01003246 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003247 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003248 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003249 return BAD_VALUE;
3250 }
Eric Laurent874c42872014-08-08 15:13:39 -07003251
Eric Laurent6a94d692014-05-20 11:18:06 -07003252 //update source and sink with our own data as the data passed in the patch may
3253 // be incomplete.
3254 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003255 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003256
Eric Laurent874c42872014-08-08 15:13:39 -07003257 for (size_t i = 0; i < patch->num_sinks; i++) {
3258 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3259 ALOGV("createAudioPatch() source device but one sink is not a device");
3260 return INVALID_OPERATION;
3261 }
3262
François Gaffie11d30102018-11-02 16:09:09 +01003263 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003264 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003265 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003266 return BAD_VALUE;
3267 }
François Gaffie11d30102018-11-02 16:09:09 +01003268 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003269
Eric Laurent3bcf8592015-04-03 12:13:24 -07003270 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003271 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003272 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003273 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003274 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3275 (srcDevice->getModuleVersionMajor() < 3) ||
3276 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003277 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003278 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003279 return INVALID_OPERATION;
3280 }
Eric Laurent874c42872014-08-08 15:13:39 -07003281 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003282 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003283 // if the sink device is reachable via an opened output stream, request to go via
3284 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003285 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003286 if (output != AUDIO_IO_HANDLE_NONE) {
3287 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3288 if (outputDesc->isDuplicated()) {
3289 return INVALID_OPERATION;
3290 }
3291 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003292 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003293 newPatch.num_sources = 2;
3294 }
Eric Laurent83b88082014-06-20 18:31:16 -07003295 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003296 }
3297 // TODO: check from routing capabilities in config file and other conflicting patches
3298
Mikhail Naganovdc769682018-05-04 15:34:08 -07003299 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3300 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003301 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3302 status);
3303 return INVALID_OPERATION;
3304 }
3305 } else {
3306 return BAD_VALUE;
3307 }
3308 } else {
3309 return BAD_VALUE;
3310 }
3311 return NO_ERROR;
3312}
3313
3314status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3315 uid_t uid)
3316{
3317 ALOGV("releaseAudioPatch() patch %d", handle);
3318
3319 ssize_t index = mAudioPatches.indexOfKey(handle);
3320
3321 if (index < 0) {
3322 return BAD_VALUE;
3323 }
3324 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3325 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3326 mUidCached, patchDesc->mUid, uid);
3327 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3328 return INVALID_OPERATION;
3329 }
3330
3331 struct audio_patch *patch = &patchDesc->mPatch;
3332 patchDesc->mUid = mUidCached;
3333 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003334 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003335 if (outputDesc == NULL) {
3336 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3337 return BAD_VALUE;
3338 }
3339
François Gaffie11d30102018-11-02 16:09:09 +01003340 setOutputDevices(outputDesc,
3341 getNewOutputDevices(outputDesc, true /*fromCache*/),
3342 true,
3343 0,
3344 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003345 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3346 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003347 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003348 if (inputDesc == NULL) {
3349 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3350 return BAD_VALUE;
3351 }
3352 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003353 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003354 true,
3355 NULL);
3356 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003357 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3358 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3359 status, patchDesc->mAfPatchHandle);
3360 removeAudioPatch(patchDesc->mHandle);
3361 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003362 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003363 } else {
3364 return BAD_VALUE;
3365 }
3366 } else {
3367 return BAD_VALUE;
3368 }
3369 return NO_ERROR;
3370}
3371
3372status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3373 struct audio_patch *patches,
3374 unsigned int *generation)
3375{
François Gaffie53615e22015-03-19 09:24:12 +01003376 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003377 return BAD_VALUE;
3378 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003379 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003380 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003381}
3382
Eric Laurente1715a42014-05-20 11:30:42 -07003383status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003384{
Eric Laurente1715a42014-05-20 11:30:42 -07003385 ALOGV("setAudioPortConfig()");
3386
3387 if (config == NULL) {
3388 return BAD_VALUE;
3389 }
3390 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3391 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003392 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3393 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003394 }
3395
Eric Laurenta121f902014-06-03 13:32:54 -07003396 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003397 if (config->type == AUDIO_PORT_TYPE_MIX) {
3398 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003399 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003400 if (outputDesc == NULL) {
3401 return BAD_VALUE;
3402 }
Eric Laurent84c70242014-06-23 08:46:27 -07003403 ALOG_ASSERT(!outputDesc->isDuplicated(),
3404 "setAudioPortConfig() called on duplicated output %d",
3405 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003406 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003407 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003408 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003409 if (inputDesc == NULL) {
3410 return BAD_VALUE;
3411 }
Eric Laurenta121f902014-06-03 13:32:54 -07003412 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003413 } else {
3414 return BAD_VALUE;
3415 }
3416 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3417 sp<DeviceDescriptor> deviceDesc;
3418 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3419 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3420 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3421 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3422 } else {
3423 return BAD_VALUE;
3424 }
3425 if (deviceDesc == NULL) {
3426 return BAD_VALUE;
3427 }
Eric Laurenta121f902014-06-03 13:32:54 -07003428 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003429 } else {
3430 return BAD_VALUE;
3431 }
3432
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003433 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003434 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3435 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003436 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003437 audioPortConfig->toAudioPortConfig(&newConfig, config);
3438 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003439 }
Eric Laurenta121f902014-06-03 13:32:54 -07003440 if (status != NO_ERROR) {
3441 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003442 }
Eric Laurente1715a42014-05-20 11:30:42 -07003443
3444 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003445}
3446
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003447void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3448{
Eric Laurentd60560a2015-04-10 11:31:20 -07003449 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003450 clearAudioPatches(uid);
3451 clearSessionRoutes(uid);
3452}
3453
Eric Laurent6a94d692014-05-20 11:18:06 -07003454void AudioPolicyManager::clearAudioPatches(uid_t uid)
3455{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003456 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003457 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3458 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003459 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003460 }
3461 }
3462}
3463
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003464void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3465 audio_io_handle_t ouptutToSkip)
3466{
François Gaffie11d30102018-11-02 16:09:09 +01003467 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3468 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003469 for (size_t j = 0; j < mOutputs.size(); j++) {
3470 if (mOutputs.keyAt(j) == ouptutToSkip) {
3471 continue;
3472 }
3473 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3474 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3475 continue;
3476 }
3477 // If the default device for this strategy is on another output mix,
3478 // invalidate all tracks in this strategy to force re connection.
3479 // Otherwise select new device on the output mix.
3480 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003481 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003482 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3483 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3484 }
3485 }
3486 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003487 setOutputDevices(
3488 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003489 }
3490 }
3491}
3492
3493void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3494{
3495 // remove output routes associated with this uid
3496 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003497 for (size_t i = 0; i < mOutputs.size(); i++) {
3498 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003499 for (const auto& client : outputDesc->getClientIterable()) {
3500 if (client->hasPreferredDevice() && client->uid() == uid) {
3501 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3502 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003503 }
3504 }
3505 }
3506 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003507 for (const auto& strategy : affectedStrategies) {
3508 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003509 }
3510
3511 // remove input routes associated with this uid
3512 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003513 for (size_t i = 0; i < mInputs.size(); i++) {
3514 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003515 for (const auto& client : inputDesc->getClientIterable()) {
3516 if (client->hasPreferredDevice() && client->uid() == uid) {
3517 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3518 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003519 }
3520 }
3521 }
3522 // reroute inputs if necessary
3523 SortedVector<audio_io_handle_t> inputsToClose;
3524 for (size_t i = 0; i < mInputs.size(); i++) {
3525 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003526 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003527 inputsToClose.add(inputDesc->mIoHandle);
3528 }
3529 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003530 for (const auto& input : inputsToClose) {
3531 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003532 }
3533}
3534
Eric Laurentd60560a2015-04-10 11:31:20 -07003535void AudioPolicyManager::clearAudioSources(uid_t uid)
3536{
3537 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003538 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3539 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003540 stopAudioSource(mAudioSources.keyAt(i));
3541 }
3542 }
3543}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003544
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003545status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3546 audio_io_handle_t *ioHandle,
3547 audio_devices_t *device)
3548{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003549 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3550 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003551 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3552 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003553
François Gaffiedf372692015-03-19 10:43:27 +01003554 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003555}
3556
Eric Laurentd60560a2015-04-10 11:31:20 -07003557status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003558 const audio_attributes_t *attributes,
3559 audio_port_handle_t *portId,
3560 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003561{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003562 ALOGV("%s", __FUNCTION__);
3563 *portId = AUDIO_PORT_HANDLE_NONE;
3564
3565 if (source == NULL || attributes == NULL || portId == NULL) {
3566 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3567 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003568 return BAD_VALUE;
3569 }
3570
Eric Laurentd60560a2015-04-10 11:31:20 -07003571 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3572 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003573 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3574 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003575 return INVALID_OPERATION;
3576 }
3577
François Gaffie11d30102018-11-02 16:09:09 +01003578 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003579 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003580 String8(source->ext.device.address),
3581 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003582 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003584 return BAD_VALUE;
3585 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003586
3587 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003588
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003589 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003590 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003591
3592 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003593 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003594 streamTypefromAttributesInt(attributes),
3595 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003596
3597 status_t status = connectAudioSource(sourceDesc);
3598 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003599 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003600 }
3601 return status;
3602}
3603
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003604status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003605{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003606 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003607
3608 // make sure we only have one patch per source.
3609 disconnectAudioSource(sourceDesc);
3610
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003611 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003612 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003613 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003614 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003615
François Gaffie11d30102018-11-02 16:09:09 +01003616 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3617 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3618 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3619 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3620 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003621
3622 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003623
François Gaffie11d30102018-11-02 16:09:09 +01003624 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3625 srcDevice->getModuleVersionMajor() >= 3 &&
3626 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3627 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003628 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003629 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003630 // create patch between src device and output device
3631 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003632 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003633 audio_attributes_t resultAttr;
3634 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3635 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3636 config.sample_rate = sourceDesc->config().sample_rate;
3637 config.channel_mask = sourceDesc->config().channel_mask;
3638 config.format = sourceDesc->config().format;
3639 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3640 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3641 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3642 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003643 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003644 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003645 return INVALID_OPERATION;
3646 }
3647 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3648 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003649 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003650 return INVALID_OPERATION;
3651 }
Eric Laurent733ce942017-12-07 12:18:25 -08003652 status_t status = outputDesc->start();
3653 if (status != NO_ERROR) {
3654 return status;
3655 }
3656
Eric Laurentd60560a2015-04-10 11:31:20 -07003657 // create a special patch with no sink and two sources:
3658 // - the second source indicates to PatchPanel through which output mix this patch should
3659 // be connected as well as the stream type for volume control
3660 // - the sink is defined by whatever output device is currently selected for the output
3661 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003662 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003663 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003664 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003665 &afPatchHandle,
3666 0);
3667 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3668 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003669 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003670 if (status != NO_ERROR) {
3671 ALOGW("%s patch panel could not connect device patch, error %d",
3672 __FUNCTION__, status);
3673 return INVALID_OPERATION;
3674 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003675
3676 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3677 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3678 return INVALID_OPERATION;
3679 }
3680 outputDesc->addClient(sourceDesc);
3681
Eric Laurentd60560a2015-04-10 11:31:20 -07003682 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003683 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003684
3685 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003686 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003687 return status;
3688 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003689 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003690 if (delayMs != 0) {
3691 usleep(delayMs * 1000);
3692 }
3693 }
3694
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003695 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3696 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003697
3698 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003699}
3700
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003701status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003702{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003703 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3704 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003705 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003706 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003707 return BAD_VALUE;
3708 }
3709 status_t status = disconnectAudioSource(sourceDesc);
3710
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003711 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003712 return status;
3713}
3714
Andy Hung2ddee192015-12-18 17:34:44 -08003715status_t AudioPolicyManager::setMasterMono(bool mono)
3716{
3717 if (mMasterMono == mono) {
3718 return NO_ERROR;
3719 }
3720 mMasterMono = mono;
3721 // if enabling mono we close all offloaded devices, which will invalidate the
3722 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3723 // for recreating the new AudioTrack as non-offloaded PCM.
3724 //
3725 // If disabling mono, we leave all tracks as is: we don't know which clients
3726 // and tracks are able to be recreated as offloaded. The next "song" should
3727 // play back offloaded.
3728 if (mMasterMono) {
3729 Vector<audio_io_handle_t> offloaded;
3730 for (size_t i = 0; i < mOutputs.size(); ++i) {
3731 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3732 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3733 offloaded.push(desc->mIoHandle);
3734 }
3735 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003736 for (const auto& handle : offloaded) {
3737 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003738 }
3739 }
3740 // update master mono for all remaining outputs
3741 for (size_t i = 0; i < mOutputs.size(); ++i) {
3742 updateMono(mOutputs.keyAt(i));
3743 }
3744 return NO_ERROR;
3745}
3746
3747status_t AudioPolicyManager::getMasterMono(bool *mono)
3748{
3749 *mono = mMasterMono;
3750 return NO_ERROR;
3751}
3752
Eric Laurentac9cef52017-06-09 15:46:26 -07003753float AudioPolicyManager::getStreamVolumeDB(
3754 audio_stream_type_t stream, int index, audio_devices_t device)
3755{
3756 return computeVolume(stream, index, device);
3757}
3758
jiabin81772902018-04-02 17:52:27 -07003759status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3760 audio_format_t *surroundFormats,
3761 bool *surroundFormatsEnabled,
3762 bool reported)
3763{
3764 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3765 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3766 return BAD_VALUE;
3767 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003768 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3769 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003770
3771 size_t formatsWritten = 0;
3772 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003773 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003774 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003775 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003776 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003777 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3778 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3779 FormatVector supportedFormats =
3780 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3781 for (size_t j = 0; j < supportedFormats.size(); j++) {
3782 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3783 formats.insert(supportedFormats[j]);
3784 } else {
3785 for (const auto& pair : mConfig.getSurroundFormats()) {
3786 if (pair.second.count(supportedFormats[j]) != 0) {
3787 formats.insert(pair.first);
3788 break;
3789 }
3790 }
3791 }
3792 }
jiabin81772902018-04-02 17:52:27 -07003793 }
3794 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003795 for (const auto& pair : mConfig.getSurroundFormats()) {
3796 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003797 }
3798 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003799 *numSurroundFormats = formats.size();
3800 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3801 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003802 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003803 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003804 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003805 bool formatEnabled = true;
3806 switch (forceUse) {
3807 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3808 formatEnabled = mManualSurroundFormats.count(format) != 0;
3809 break;
3810 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3811 formatEnabled = false;
3812 break;
3813 default: // AUTO or ALWAYS => true
3814 break;
jiabin81772902018-04-02 17:52:27 -07003815 }
3816 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3817 }
jiabin81772902018-04-02 17:52:27 -07003818 }
3819 return NO_ERROR;
3820}
3821
3822status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3823{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003824 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003825 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3826 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003827 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003828 return BAD_VALUE;
3829 }
3830
Mikhail Naganov100f0122018-11-29 11:22:16 -08003831 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3832 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003833 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003834 return INVALID_OPERATION;
3835 }
3836
Mikhail Naganov100f0122018-11-29 11:22:16 -08003837 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003838 return NO_ERROR;
3839 }
3840
Mikhail Naganov100f0122018-11-29 11:22:16 -08003841 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003842 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003843 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003844 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003845 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003846 }
3847 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003848 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003849 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003850 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003851 }
3852 }
3853
3854 sp<SwAudioOutputDescriptor> outputDesc;
3855 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003856 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003857 AUDIO_DEVICE_OUT_HDMI);
3858 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3859 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003860 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003861 String8 name = hdmiOutputDevices[i]->getName();
3862 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3863 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3864 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003865 name.c_str(),
3866 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003867 if (status != NO_ERROR) {
3868 continue;
3869 }
3870 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3871 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3872 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003873 name.c_str(),
3874 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003875 profileUpdated |= (status == NO_ERROR);
3876 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003877 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003878 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003879 AUDIO_DEVICE_IN_HDMI);
3880 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3881 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003882 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003883 String8 name = hdmiInputDevices[i]->getName();
3884 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3885 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3886 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003887 name.c_str(),
3888 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003889 if (status != NO_ERROR) {
3890 continue;
3891 }
3892 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3893 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3894 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003895 name.c_str(),
3896 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003897 profileUpdated |= (status == NO_ERROR);
3898 }
3899
jiabin81772902018-04-02 17:52:27 -07003900 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003901 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003902 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003903 }
3904
3905 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3906}
3907
Eric Laurentf32108e2018-10-04 17:22:04 -07003908void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003909{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003910 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003911
Eric Laurenta9f86652018-11-28 17:23:11 -08003912 for (size_t i = 0; i < mInputs.size(); i++) {
3913 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3914 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003915 for (const auto& client : clients) {
3916 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003917 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003918 }
3919 }
3920 }
3921}
3922
jiabin6012f912018-11-02 17:06:30 -07003923bool AudioPolicyManager::isHapticPlaybackSupported()
3924{
3925 for (const auto& hwModule : mHwModules) {
3926 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3927 for (const auto &outProfile : outputProfiles) {
3928 struct audio_port audioPort;
3929 outProfile->toAudioPort(&audioPort);
3930 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3931 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3932 return true;
3933 }
3934 }
3935 }
3936 }
3937 return false;
3938}
3939
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003940status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003941{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003942 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003943
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003944 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003945 if (patchDesc == 0) {
3946 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003947 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003948 return BAD_VALUE;
3949 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003950 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003951
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003952 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003953 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003954 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003955 if (status == NO_ERROR) {
3956 swOutputDesc->stop();
3957 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003958 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3959 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003960 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003961 if (hwOutputDesc != 0) {
3962 // release patch between src device and output device
3963 // close Hwoutput and remove from mHwOutputs
3964 } else {
3965 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3966 }
3967 }
3968 return NO_ERROR;
3969}
3970
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003971sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003972 audio_io_handle_t output, routing_strategy strategy)
3973{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003974 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003975 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003976 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3977 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003978 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003979 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003980 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3981 source = sourceDesc;
3982 break;
3983 }
3984 }
3985 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003986}
3987
Eric Laurente552edb2014-03-10 17:42:56 -07003988// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003989// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003990// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003991uint32_t AudioPolicyManager::nextAudioPortGeneration()
3992{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003993 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003994}
3995
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003996// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3997static const char *kConfigLocationList[] =
3998 {"/odm/etc", "/vendor/etc", "/system/etc"};
3999static const int kConfigLocationListSize =
4000 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
4001
4002static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4003 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004004 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004005 status_t ret;
4006
Petri Gyntherf497f292018-04-17 18:46:10 -07004007 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
4008 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4009 // A2DP offload supported but disabled: try to use special XML file
4010 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4011 }
4012 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4013
4014 for (const char* fileName : fileNames) {
4015 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004016 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4017 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004018 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004019 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004020 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004021 return ret;
4022 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004023 }
4024 }
4025 return ret;
4026}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004027
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004028AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4029 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004030 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004031 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004032 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004033 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004034 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004035 mVolumeCurves(new VolumeCurvesCollection()),
4036 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004037 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004038 mAudioPortGeneration(1),
4039 mBeaconMuteRefCount(0),
4040 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004041 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004042 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004043 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004044 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004045{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004046}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004047
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004048AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4049 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4050{
4051 loadConfig();
4052 initialize();
4053}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004054
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004055// This check is to catch any legacy platform updating to Q without having
4056// switched to XML since its deprecation on O.
4057// TODO: after Q release, remove this check and flag as XML is now the only
4058// option and all legacy platform should have transitioned to XML.
4059#ifndef USE_XML_AUDIO_POLICY_CONF
4060#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004061#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004062
4063void AudioPolicyManager::loadConfig() {
4064 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004065 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004066 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004067 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004068}
4069
4070status_t AudioPolicyManager::initialize() {
4071 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004072
4073 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004074 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4075 if (!engineInstance) {
4076 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004077 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004078 }
4079 // Retrieve the Policy Manager Interface
4080 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4081 if (mEngine == NULL) {
4082 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004083 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004084 }
4085 mEngine->setObserver(this);
4086 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004087 if (status != NO_ERROR) {
4088 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4089 return status;
4090 }
François Gaffie2110e042015-03-24 08:41:51 +01004091
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004093 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004094 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004095 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004096 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4097 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004098 continue;
4099 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004100 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004101 // open all output streams needed to access attached devices
4102 // except for direct output streams that are only opened when they are actually
4103 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004104 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004105 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004106 if (!outProfile->canOpenNewIo()) {
4107 ALOGE("Invalid Output profile max open count %u for profile %s",
4108 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4109 continue;
4110 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004111 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004112 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 continue;
4114 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004115 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004116 mTtsOutputAvailable = true;
4117 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004118
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004119 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004120 continue;
4121 }
François Gaffie11d30102018-11-02 16:09:09 +01004122 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4123 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4124 sp<DeviceDescriptor> supportedDevice = 0;
4125 if (supportedDevices.contains(mDefaultOutputDevice)) {
4126 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004127 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004128 // choose first device present in profile's SupportedDevices also part of
4129 // mAvailableOutputDevices.
4130 if (availProfileDevices.isEmpty()) {
4131 continue;
4132 }
4133 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004134 }
François Gaffie11d30102018-11-02 16:09:09 +01004135 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004136 continue;
4137 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004138 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4139 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004140 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004141 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4142 AUDIO_STREAM_DEFAULT,
4143 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004144 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004145 ALOGW("Cannot open output stream for devices %s on hw module %s",
4146 supportedDevice->toString().c_str(), hwModule->getName());
4147 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004148 }
François Gaffie11d30102018-11-02 16:09:09 +01004149 for (const auto &device : availProfileDevices) {
4150 // give a valid ID to an attached device once confirmed it is reachable
4151 if (!device->isAttached()) {
4152 device->attach(hwModule);
4153 }
4154 }
4155 if (mPrimaryOutput == 0 &&
4156 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4157 mPrimaryOutput = outputDesc;
4158 }
4159 addOutput(output, outputDesc);
4160 setOutputDevices(outputDesc,
4161 DeviceVector(supportedDevice),
4162 true,
4163 0,
4164 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004165 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004166 // open input streams needed to access attached devices to validate
4167 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004168 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004169 if (!inProfile->canOpenNewIo()) {
4170 ALOGE("Invalid Input profile max open count %u for profile %s",
4171 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4172 continue;
4173 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004174 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004175 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 continue;
4177 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004178 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004179 // available input devices
4180 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4181 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4182 if (availProfileDevices.isEmpty()) {
4183 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004184 continue;
4185 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004186 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004187 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004188
Eric Laurentd78f1532014-09-16 16:38:20 -07004189 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004190 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004191 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004192 AUDIO_SOURCE_MIC,
4193 AUDIO_INPUT_FLAG_NONE,
4194 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004195 if (status != NO_ERROR) {
4196 ALOGW("Cannot open input stream for device %s on hw module %s",
4197 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004198 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004199 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004200 }
François Gaffie11d30102018-11-02 16:09:09 +01004201 for (const auto &device : availProfileDevices) {
4202 // give a valid ID to an attached device once confirmed it is reachable
4203 if (!device->isAttached()) {
4204 device->attach(hwModule);
4205 device->importAudioPort(inProfile, true);
4206 }
4207 }
4208 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004209 }
4210 }
4211 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004212 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004213 for (size_t i = 0; i < devices.size();) {
4214 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004215 if (!device->isAttached()) {
4216 ALOGW("device %s is unreachable", device->toString().c_str());
4217 devices.remove(device);
4218 continue;
4219 }
4220 // Device is now validated and can be appended to the available devices of the engine
4221 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004222 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004223 }
François Gaffie11d30102018-11-02 16:09:09 +01004224 };
4225 checkAndSetAvailable(mAvailableOutputDevices);
4226 checkAndSetAvailable(mAvailableInputDevices);
4227
Eric Laurent3a4311c2014-03-17 12:00:47 -07004228 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004229 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4230 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4231 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004232 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004233 }
jiabin9ff780e2018-03-19 18:19:52 -07004234 // If microphones address is empty, set it according to device type
4235 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004236 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004237 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004238 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004239 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004240 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004241 }
4242 }
4243 }
Eric Laurente552edb2014-03-10 17:42:56 -07004244
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004245 if (mPrimaryOutput == 0) {
4246 ALOGE("Failed to open primary output");
4247 status = NO_INIT;
4248 }
Eric Laurente552edb2014-03-10 17:42:56 -07004249
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004250 // Silence ALOGV statements
4251 property_set("log.tag." LOG_TAG, "D");
4252
Eric Laurente552edb2014-03-10 17:42:56 -07004253 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004254 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004255}
4256
Eric Laurente0720872014-03-11 09:30:41 -07004257AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004258{
Eric Laurente552edb2014-03-10 17:42:56 -07004259 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004260 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004261 }
4262 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004263 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004264 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004265 mAvailableOutputDevices.clear();
4266 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004267 mOutputs.clear();
4268 mInputs.clear();
4269 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004270 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004271 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004272}
4273
Eric Laurente0720872014-03-11 09:30:41 -07004274status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004275{
Eric Laurent87ffa392015-05-22 10:32:38 -07004276 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004277}
4278
Eric Laurente552edb2014-03-10 17:42:56 -07004279// ---
4280
Eric Laurent98e38192018-02-15 18:31:53 -08004281void AudioPolicyManager::addOutput(audio_io_handle_t output,
4282 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004283{
Eric Laurent1c333e22014-05-20 10:48:17 -07004284 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004285 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004286 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004287 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004288 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004289}
4290
François Gaffie53615e22015-03-19 09:24:12 +01004291void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4292{
4293 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004294 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004295}
4296
Eric Laurent98e38192018-02-15 18:31:53 -08004297void AudioPolicyManager::addInput(audio_io_handle_t input,
4298 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004299{
Eric Laurent1c333e22014-05-20 10:48:17 -07004300 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004302}
Eric Laurente552edb2014-03-10 17:42:56 -07004303
François Gaffie11d30102018-11-02 16:09:09 +01004304status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004305 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004306 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004307{
François Gaffie11d30102018-11-02 16:09:09 +01004308 audio_devices_t deviceType = device->type();
4309 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004310 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004311
François Gaffie11d30102018-11-02 16:09:09 +01004312 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004313 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004314 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004315 }
Eric Laurente552edb2014-03-10 17:42:56 -07004316
Eric Laurent3b73df72014-03-11 09:06:29 -07004317 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004318 // first list already open outputs that can be routed to this device
4319 for (size_t i = 0; i < mOutputs.size(); i++) {
4320 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004321 if (!desc->isDuplicated() && desc->supportsDevice(device)
4322 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004323 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4324 mOutputs.keyAt(i), device->toString().c_str());
4325 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004326 }
4327 }
4328 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004329 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004330 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004331 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4332 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004333 if (profile->supportsDevice(device)) {
4334 profiles.add(profile);
4335 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4336 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004337 }
4338 }
4339 }
4340
Eric Laurent7b279bb2015-12-14 10:18:23 -08004341 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004342
Eric Laurente552edb2014-03-10 17:42:56 -07004343 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004344 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004345 return BAD_VALUE;
4346 }
4347
4348 // open outputs for matching profiles if needed. Direct outputs are also opened to
4349 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4350 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004351 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004352
4353 // nothing to do if one output is already opened for this profile
4354 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004355 for (j = 0; j < outputs.size(); j++) {
4356 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004357 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004358 // matching profile: save the sample rates, format and channel masks supported
4359 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004360 if (audio_device_is_digital(deviceType)) {
4361 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004362 }
Eric Laurente552edb2014-03-10 17:42:56 -07004363 break;
4364 }
4365 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004366 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004367 continue;
4368 }
4369
Eric Laurent3974e3b2017-12-07 17:58:43 -08004370 if (!profile->canOpenNewIo()) {
4371 ALOGW("Max Output number %u already opened for this profile %s",
4372 profile->maxOpenCount, profile->getTagName().c_str());
4373 continue;
4374 }
4375
Eric Laurent83efe1c2017-07-09 16:51:08 -07004376 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004377 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004378 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004379 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004380 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004381 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004382
Eric Laurentfe231122017-11-17 17:48:06 -08004383 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004384 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004385 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004386 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004387 mpClientInterface->setParameters(output, String8(param));
4388 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004389 }
François Gaffie11d30102018-11-02 16:09:09 +01004390 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004391 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004392 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004393 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004394 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004395 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004396 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004397 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004398 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4399 profile->pickAudioProfile(
4400 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004401 config.offload_info.sample_rate = config.sample_rate;
4402 config.offload_info.channel_mask = config.channel_mask;
4403 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004404
François Gaffie11d30102018-11-02 16:09:09 +01004405 status_t status = desc->open(&config, DeviceVector(device),
4406 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004407 AUDIO_OUTPUT_FLAG_NONE, &output);
4408 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004409 output = AUDIO_IO_HANDLE_NONE;
4410 }
Eric Laurentd4692962014-05-05 18:13:44 -07004411 }
4412
Eric Laurentcf2c0212014-07-25 16:20:43 -07004413 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004414 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004415 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004416 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004417 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4418 policyMix->setOutput(desc);
4419 desc->mPolicyMix = policyMix->getMix();
4420 } else {
4421 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004422 address.string());
4423 }
François Gaffie036e1e92015-03-19 10:16:24 +01004424
Eric Laurent87ffa392015-05-22 10:32:38 -07004425 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4426 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004427 // no duplicated output for direct outputs and
4428 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004429 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004430
Eric Laurentd4692962014-05-05 18:13:44 -07004431 //TODO: configure audio effect output stage here
4432
4433 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004434 sp<SwAudioOutputDescriptor> dupOutputDesc =
4435 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4436 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4437 &duplicatedOutput);
4438 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004439 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004440 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004441 } else {
4442 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004443 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004444 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004445 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004447 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004448 }
Eric Laurente552edb2014-03-10 17:42:56 -07004449 }
4450 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004451 } else {
4452 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004453 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004454 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004455 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004456 profiles.removeAt(profile_index);
4457 profile_index--;
4458 } else {
4459 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004460 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004461 if (audio_device_is_digital(deviceType)) {
4462 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004463 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004464
François Gaffie11d30102018-11-02 16:09:09 +01004465 if (device_distinguishes_on_address(deviceType)) {
4466 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4467 device->toString().c_str());
4468 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4469 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004470 }
Eric Laurente552edb2014-03-10 17:42:56 -07004471 ALOGV("checkOutputsForDevice(): adding output %d", output);
4472 }
4473 }
4474
4475 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004476 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004477 return BAD_VALUE;
4478 }
Eric Laurentd4692962014-05-05 18:13:44 -07004479 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004480 // check if one opened output is not needed any more after disconnecting one device
4481 for (size_t i = 0; i < mOutputs.size(); i++) {
4482 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004483 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004484 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004485 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4486 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004487 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004488 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004489 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4490 mOutputs.keyAt(i));
4491 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004492 }
Eric Laurente552edb2014-03-10 17:42:56 -07004493 }
4494 }
Eric Laurentd4692962014-05-05 18:13:44 -07004495 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004496 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004497 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4498 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004499 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004500 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004501 "clearing direct output profile %zu on module %s",
4502 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004503 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004504 }
4505 }
4506 }
4507 }
4508 return NO_ERROR;
4509}
4510
François Gaffie11d30102018-11-02 16:09:09 +01004511status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004512 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004513 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004514{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004515 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004516
François Gaffie11d30102018-11-02 16:09:09 +01004517 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004518 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004519 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004520 }
4521
Eric Laurentd4692962014-05-05 18:13:44 -07004522 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4523 // first list already open inputs that can be routed to this device
4524 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4525 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004526 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004527 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4528 inputs.add(mInputs.keyAt(input_index));
4529 }
4530 }
4531
4532 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004533 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004534 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004535 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004536 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004537 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004538 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004539
François Gaffie11d30102018-11-02 16:09:09 +01004540 if (profile->supportsDevice(device)) {
4541 profiles.add(profile);
4542 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4543 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004544 }
4545 }
4546 }
4547
4548 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004549 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004550 return BAD_VALUE;
4551 }
4552
4553 // open inputs for matching profiles if needed. Direct inputs are also opened to
4554 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4555 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4556
Eric Laurent1c333e22014-05-20 10:48:17 -07004557 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004558
Eric Laurentd4692962014-05-05 18:13:44 -07004559 // nothing to do if one input is already opened for this profile
4560 size_t input_index;
4561 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4562 desc = mInputs.valueAt(input_index);
4563 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004564 if (audio_device_is_digital(device->type())) {
4565 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004566 }
Eric Laurentd4692962014-05-05 18:13:44 -07004567 break;
4568 }
4569 }
4570 if (input_index != mInputs.size()) {
4571 continue;
4572 }
4573
Eric Laurent3974e3b2017-12-07 17:58:43 -08004574 if (!profile->canOpenNewIo()) {
4575 ALOGW("Max Input number %u already opened for this profile %s",
4576 profile->maxOpenCount, profile->getTagName().c_str());
4577 continue;
4578 }
4579
Eric Laurentfe231122017-11-17 17:48:06 -08004580 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004581 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004582 status_t status = desc->open(nullptr,
4583 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004584 AUDIO_SOURCE_MIC,
4585 AUDIO_INPUT_FLAG_NONE,
4586 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004587
Eric Laurentcf2c0212014-07-25 16:20:43 -07004588 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004589 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004590 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004591 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004592 mpClientInterface->setParameters(input, String8(param));
4593 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004594 }
François Gaffie11d30102018-11-02 16:09:09 +01004595 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004596 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004597 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004598 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004599 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004600 }
4601
4602 if (input != 0) {
4603 addInput(input, desc);
4604 }
4605 } // endif input != 0
4606
Eric Laurentcf2c0212014-07-25 16:20:43 -07004607 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004608 ALOGW("%s could not open input for device %s", __func__,
4609 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004610 profiles.removeAt(profile_index);
4611 profile_index--;
4612 } else {
4613 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004614 if (audio_device_is_digital(device->type())) {
4615 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004616 }
Eric Laurentd4692962014-05-05 18:13:44 -07004617 ALOGV("checkInputsForDevice(): adding input %d", input);
4618 }
4619 } // end scan profiles
4620
4621 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004622 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004623 return BAD_VALUE;
4624 }
4625 } else {
4626 // Disconnect
4627 // check if one opened input is not needed any more after disconnecting one device
4628 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4629 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004630 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004631 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4632 mInputs.keyAt(input_index));
4633 inputs.add(mInputs.keyAt(input_index));
4634 }
4635 }
4636 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004637 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004638 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004639 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004640 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004641 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004642 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004643 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4644 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004645 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004646 }
4647 }
4648 }
4649 } // end disconnect
4650
4651 return NO_ERROR;
4652}
4653
4654
Eric Laurente0720872014-03-11 09:30:41 -07004655void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004656{
4657 ALOGV("closeOutput(%d)", output);
4658
Eric Laurentc75307b2015-03-17 15:29:32 -07004659 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004660 if (outputDesc == NULL) {
4661 ALOGW("closeOutput() unknown output %d", output);
4662 return;
4663 }
François Gaffie036e1e92015-03-19 10:16:24 +01004664 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004665
Eric Laurente552edb2014-03-10 17:42:56 -07004666 // look for duplicated outputs connected to the output being removed.
4667 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004668 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004669 if (dupOutputDesc->isDuplicated() &&
4670 (dupOutputDesc->mOutput1 == outputDesc ||
4671 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004672 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004673 if (dupOutputDesc->mOutput1 == outputDesc) {
4674 outputDesc2 = dupOutputDesc->mOutput2;
4675 } else {
4676 outputDesc2 = dupOutputDesc->mOutput1;
4677 }
4678 // As all active tracks on duplicated output will be deleted,
4679 // and as they were also referenced on the other output, the reference
4680 // count for their stream type must be adjusted accordingly on
4681 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004682 const bool wasActive = outputDesc2->isActive();
4683 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4684 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
Eric Laurent733ce942017-12-07 12:18:25 -08004686 // stop() will be a no op if the output is still active but is needed in case all
4687 // active streams refcounts where cleared above
4688 if (wasActive) {
4689 outputDesc2->stop();
4690 }
Eric Laurente552edb2014-03-10 17:42:56 -07004691 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4692 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4693
4694 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004695 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004696 }
4697 }
4698
Eric Laurent05b90f82014-08-27 15:32:29 -07004699 nextAudioPortGeneration();
4700
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004701 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004702 if (index >= 0) {
4703 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004704 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004705 mAudioPatches.removeItemsAt(index);
4706 mpClientInterface->onAudioPatchListUpdate();
4707 }
4708
Eric Laurentfe231122017-11-17 17:48:06 -08004709 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004710
François Gaffie53615e22015-03-19 09:24:12 +01004711 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004713
4714 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4715 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004716 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004717 bool directOutputOpen = false;
4718 for (size_t i = 0; i < mOutputs.size(); i++) {
4719 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4720 directOutputOpen = true;
4721 break;
4722 }
4723 }
4724 if (!directOutputOpen) {
4725 ALOGV("no direct outputs open, reset MSD patch");
4726 setMsdPatch();
4727 }
4728 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004729}
4730
4731void AudioPolicyManager::closeInput(audio_io_handle_t input)
4732{
4733 ALOGV("closeInput(%d)", input);
4734
4735 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4736 if (inputDesc == NULL) {
4737 ALOGW("closeInput() unknown input %d", input);
4738 return;
4739 }
4740
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004742
François Gaffie11d30102018-11-02 16:09:09 +01004743 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004744 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004745 if (index >= 0) {
4746 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004747 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004748 mAudioPatches.removeItemsAt(index);
4749 mpClientInterface->onAudioPatchListUpdate();
4750 }
4751
Eric Laurentfe231122017-11-17 17:48:06 -08004752 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004753 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004754
François Gaffie11d30102018-11-02 16:09:09 +01004755 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4756 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004757 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4758 SoundTrigger::setCaptureState(false);
4759 }
Eric Laurente552edb2014-03-10 17:42:56 -07004760}
4761
François Gaffie11d30102018-11-02 16:09:09 +01004762SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4763 const DeviceVector &devices,
4764 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004765{
4766 SortedVector<audio_io_handle_t> outputs;
4767
François Gaffie11d30102018-11-02 16:09:09 +01004768 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004769 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004770 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004771 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004772 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004773 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4774 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004775 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004776 outputs.add(openOutputs.keyAt(i));
4777 }
4778 }
4779 return outputs;
4780}
4781
Mikhail Naganov37977152018-07-11 15:54:44 -07004782void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4783{
4784 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4785 // output is suspended before any tracks are moved to it
4786 checkA2dpSuspend();
4787 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004788 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004789 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004790 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004791 setMsdPatch();
4792 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004796{
François Gaffie11d30102018-11-02 16:09:09 +01004797 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4798 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4799 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4800 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004801
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004802 // also take into account external policy-related changes: add all outputs which are
4803 // associated with policies in the "before" and "after" output vectors
4804 ALOGVV("checkOutputForStrategy(): policy related outputs");
4805 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004806 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004807 if (desc != 0 && desc->mPolicyMix != NULL) {
4808 srcOutputs.add(desc->mIoHandle);
4809 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4810 }
4811 }
4812 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004813 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004814 if (desc != 0 && desc->mPolicyMix != NULL) {
4815 dstOutputs.add(desc->mIoHandle);
4816 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4817 }
4818 }
4819
Francois Gaffie716e1432019-01-14 16:58:59 +01004820 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004821 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4822 // audio from invalidated tracks will be rendered when unmuting
4823 uint32_t maxLatency = 0;
4824 for (audio_io_handle_t srcOut : srcOutputs) {
4825 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4826 if (desc != 0 && maxLatency < desc->latency()) {
4827 maxLatency = desc->latency();
4828 }
4829 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004830 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4831 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4832 std::to_string(srcOutputs[0]).c_str(),
4833 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004834 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004835 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004836 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4837 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004838 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004839 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4840 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004841 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004842 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004843 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004844 if (source != 0){
4845 connectAudioSource(source);
4846 }
Eric Laurente552edb2014-03-10 17:42:56 -07004847 }
4848
4849 // Move effects associated to this strategy from previous output to new output
4850 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004851 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004852 }
4853 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004854 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004855 if (getStrategy((audio_stream_type_t)i) == strategy) {
4856 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004857 }
4858 }
4859 }
4860}
4861
Eric Laurente0720872014-03-11 09:30:41 -07004862void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004863{
François Gaffie2110e042015-03-24 08:41:51 +01004864 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004865 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004866 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004867 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004868 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004869 checkOutputForStrategy(STRATEGY_SONIFICATION);
4870 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004871 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004872 checkOutputForStrategy(STRATEGY_MEDIA);
4873 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004874 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004875}
4876
Eric Laurente0720872014-03-11 09:30:41 -07004877void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004878{
François Gaffie53615e22015-03-19 09:24:12 +01004879 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004880 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004881 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004882 return;
4883 }
4884
Eric Laurent3a4311c2014-03-17 12:00:47 -07004885 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004886 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4887 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4888 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004889
4890 // if suspended, restore A2DP output if:
4891 // ((SCO device is NOT connected) ||
4892 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4893 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004894 //
Eric Laurentf732e072016-08-03 19:30:28 -07004895 // if not suspended, suspend A2DP output if:
4896 // (SCO device is connected) &&
4897 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4898 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004899 //
4900 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004901 if (!isScoConnected ||
4902 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4903 AUDIO_POLICY_FORCE_BT_SCO) &&
4904 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4905 AUDIO_POLICY_FORCE_BT_SCO) &&
4906 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004907 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004908
4909 mpClientInterface->restoreOutput(a2dpOutput);
4910 mA2dpSuspended = false;
4911 }
4912 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004913 if (isScoConnected &&
4914 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4915 AUDIO_POLICY_FORCE_BT_SCO) ||
4916 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4917 AUDIO_POLICY_FORCE_BT_SCO) ||
4918 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004919 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004920
4921 mpClientInterface->suspendOutput(a2dpOutput);
4922 mA2dpSuspended = true;
4923 }
4924 }
4925}
4926
Eric Laurent97ac8712018-07-27 18:59:02 -07004927template <class IoDescriptor, class Filter>
4928sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4929 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4930{
4931 auto activeClients = desc->clientsList(true /*activeOnly*/);
4932 auto activeClientsWithRoute =
4933 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4934 active = activeClients.size() > 0;
4935 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4936 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4937 }
4938 return nullptr;
4939}
4940
4941template <class IoCollection, class Filter>
4942sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4943 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4944{
4945 sp<DeviceDescriptor> device;
4946 for (size_t i = 0; i < ioCollection.size(); i++) {
4947 auto desc = ioCollection.valueAt(i);
4948 bool active;
4949 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4950 if (active && curDevice == nullptr) {
4951 return nullptr;
4952 } else if (curDevice != nullptr) {
4953 device = curDevice;
4954 }
4955 }
4956 return device;
4957}
4958
François Gaffie11d30102018-11-02 16:09:09 +01004959DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4960 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004961{
François Gaffie11d30102018-11-02 16:09:09 +01004962 DeviceVector devices;
4963
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004964 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 if (index >= 0) {
4966 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4967 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004968 ALOGV("%s device %s forced by patch %d", __func__,
4969 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4970 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 }
4972 }
4973
Eric Laurent97ac8712018-07-27 18:59:02 -07004974 // Honor explicit routing requests only if no client using default routing is active on this
4975 // input: a specific app can not force routing for other apps by setting a preferred device.
4976 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004977 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004978 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004979 if (device != nullptr) {
4980 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004981 }
4982
François Gaffiea807ef92018-11-05 10:44:33 +01004983 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
4984 // of setForceUse / Default Bus device here
4985 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
4986 if (device != nullptr) {
4987 return DeviceVector(device);
4988 }
4989
Eric Laurente552edb2014-03-10 17:42:56 -07004990 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004991 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004992 // use device for strategy enforced audible
4993 // 2: we are in call or the strategy phone is active on the output:
4994 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004995 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004996 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004997 // 4: the strategy for enforced audible is active but not enforced on the output:
4998 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004999 // 5: the strategy accessibility is active on the output:
5000 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07005001 // 6: the strategy "respectful" sonification is active on the output:
5002 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08005003 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07005004 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08005005 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07005006 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08005007 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005008 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07005009
5010 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
5011 // with a refined rule considering mutually exclusive devices (using same backend)
5012 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01005013 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005014 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01005015 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005016 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07005017 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005018 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08005019 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01005020 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07005021 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005022 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005023 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01005024 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005025 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01005026 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005027 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01005028 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005029 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01005030 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005031 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01005032 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005033 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01005034 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005035 }
5036
François Gaffie11d30102018-11-02 16:09:09 +01005037 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
5038 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005039}
5040
François Gaffie11d30102018-11-02 16:09:09 +01005041sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5042 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005043{
François Gaffie11d30102018-11-02 16:09:09 +01005044 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005045
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005046 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 if (index >= 0) {
5048 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5049 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005050 ALOGV("getNewInputDevice() device %s forced by patch %d",
5051 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5052 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 }
5054 }
5055
Eric Laurent97ac8712018-07-27 18:59:02 -07005056 // Honor explicit routing requests only if no client using default routing is active on this
5057 // input: a specific app can not force routing for other apps by setting a preferred device.
5058 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005059 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5060 if (device != nullptr) {
5061 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005062 }
5063
Eric Laurentdc95a252018-04-12 12:46:56 -07005064 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005065 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005066 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5067 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5068 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005069 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005070 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5071 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005072 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005073
Eric Laurente552edb2014-03-10 17:42:56 -07005074 return device;
5075}
5076
Eric Laurent794fde22016-03-11 09:50:45 -08005077bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5078 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005079 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005080}
5081
Eric Laurente0720872014-03-11 09:30:41 -07005082uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005083 return (uint32_t)getStrategy(stream);
5084}
5085
Eric Laurente0720872014-03-11 09:30:41 -07005086audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005087 // By checking the range of stream before calling getStrategy, we avoid
5088 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5089 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005090 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 return AUDIO_DEVICE_NONE;
5092 }
François Gaffie11d30102018-11-02 16:09:09 +01005093 DeviceVector activeDevices;
5094 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005095 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5096 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005097 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 }
Eric Laurent794fde22016-03-11 09:50:45 -08005099 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005100 DeviceVector curDevices =
5101 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5102 devices.merge(curDevices);
5103 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005104 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005105 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005106 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005107 }
5108 }
Eric Laurente552edb2014-03-10 17:42:56 -07005109 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005110
Eric Laurentb0688d62018-08-14 15:49:18 -07005111 // Favor devices selected on active streams if any to report correct device in case of
5112 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005113 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005114 devices = activeDevices;
5115 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005116 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5117 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005118 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5119 if (!speakerSafeDevices.isEmpty()) {
5120 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5121 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005122 }
François Gaffie11d30102018-11-02 16:09:09 +01005123 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005124}
5125
François Gaffie2110e042015-03-24 08:41:51 +01005126routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5127{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005128 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005129 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005130}
5131
Eric Laurent97ac8712018-07-27 18:59:02 -07005132routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005133 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005134 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005135 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005136 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005137 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005138 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005139 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005140 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005141 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005142}
5143
Eric Laurente0720872014-03-11 09:30:41 -07005144void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005145 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005146 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005147 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5148 updateDevicesAndOutputs();
5149 break;
5150 default:
5151 break;
5152 }
5153}
5154
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005155uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005156
5157 // skip beacon mute management if a dedicated TTS output is available
5158 if (mTtsOutputAvailable) {
5159 return 0;
5160 }
5161
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005162 switch(event) {
5163 case STARTING_OUTPUT:
5164 mBeaconMuteRefCount++;
5165 break;
5166 case STOPPING_OUTPUT:
5167 if (mBeaconMuteRefCount > 0) {
5168 mBeaconMuteRefCount--;
5169 }
5170 break;
5171 case STARTING_BEACON:
5172 mBeaconPlayingRefCount++;
5173 break;
5174 case STOPPING_BEACON:
5175 if (mBeaconPlayingRefCount > 0) {
5176 mBeaconPlayingRefCount--;
5177 }
5178 break;
5179 }
5180
5181 if (mBeaconMuteRefCount > 0) {
5182 // any playback causes beacon to be muted
5183 return setBeaconMute(true);
5184 } else {
5185 // no other playback: unmute when beacon starts playing, mute when it stops
5186 return setBeaconMute(mBeaconPlayingRefCount == 0);
5187 }
5188}
5189
5190uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5191 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5192 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5193 // keep track of muted state to avoid repeating mute/unmute operations
5194 if (mBeaconMuted != mute) {
5195 // mute/unmute AUDIO_STREAM_TTS on all outputs
5196 ALOGV("\t muting %d", mute);
5197 uint32_t maxLatency = 0;
5198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005200 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005201 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005202 0 /*delay*/, AUDIO_DEVICE_NONE);
5203 const uint32_t latency = desc->latency() * 2;
5204 if (latency > maxLatency) {
5205 maxLatency = latency;
5206 }
5207 }
5208 mBeaconMuted = mute;
5209 return maxLatency;
5210 }
5211 return 0;
5212}
5213
François Gaffie11d30102018-11-02 16:09:09 +01005214DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005215{
Eric Laurent97ac8712018-07-27 18:59:02 -07005216 // Honor explicit routing requests only if all active clients have a preferred route in which
5217 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005218 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5219 if (device != nullptr) {
5220 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005221 }
5222
Eric Laurente552edb2014-03-10 17:42:56 -07005223 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005224 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5225 mDevicesForStrategy[strategy].toString().c_str());
5226 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005227 }
François Gaffie11d30102018-11-02 16:09:09 +01005228 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005229}
5230
Eric Laurente0720872014-03-11 09:30:41 -07005231void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005232{
5233 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005234 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005235 }
5236 mPreviousOutputs = mOutputs;
5237}
5238
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005239uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005240 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005241 uint32_t delayMs)
5242{
5243 // mute/unmute strategies using an incompatible device combination
5244 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5245 // if unmuting, unmute only after the specified delay
5246 if (outputDesc->isDuplicated()) {
5247 return 0;
5248 }
5249
5250 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005251 audio_devices_t deviceType = outputDesc->devices().types();
5252 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005253
5254 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005255 audio_devices_t curDeviceType =
5256 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5257 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5258 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005259 bool doMute = false;
5260
5261 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5262 doMute = true;
5263 outputDesc->mStrategyMutedByDevice[i] = true;
5264 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5265 doMute = true;
5266 outputDesc->mStrategyMutedByDevice[i] = false;
5267 }
Eric Laurent99401132014-05-07 19:48:15 -07005268 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005269 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005270 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005271 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005272 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005273 continue;
5274 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005275 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005276 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005277 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005278 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005279 if (mute) {
5280 // FIXME: should not need to double latency if volume could be applied
5281 // immediately by the audioflinger mixer. We must account for the delay
5282 // between now and the next time the audioflinger thread for this output
5283 // will process a buffer (which corresponds to one buffer size,
5284 // usually 1/2 or 1/4 of the latency).
5285 if (muteWaitMs < desc->latency() * 2) {
5286 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005287 }
5288 }
5289 }
5290 }
5291 }
5292 }
5293
Eric Laurent99401132014-05-07 19:48:15 -07005294 // temporary mute output if device selection changes to avoid volume bursts due to
5295 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005296 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005297 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5298 // temporary mute duration is conservatively set to 4 times the reported latency
5299 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5300 if (muteWaitMs < tempMuteWaitMs) {
5301 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005302 }
Eric Laurentdc462862016-07-19 12:29:53 -07005303
Eric Laurent99401132014-05-07 19:48:15 -07005304 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005305 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005306 // make sure that we do not start the temporary mute period too early in case of
5307 // delayed device change
5308 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005309 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005310 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005311 }
5312 }
5313 }
5314
Eric Laurente552edb2014-03-10 17:42:56 -07005315 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5316 if (muteWaitMs > delayMs) {
5317 muteWaitMs -= delayMs;
5318 usleep(muteWaitMs * 1000);
5319 return muteWaitMs;
5320 }
5321 return 0;
5322}
5323
François Gaffie11d30102018-11-02 16:09:09 +01005324uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5325 const DeviceVector &devices,
5326 bool force,
5327 int delayMs,
5328 audio_patch_handle_t *patchHandle,
5329 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005330{
François Gaffie11d30102018-11-02 16:09:09 +01005331 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005332 uint32_t muteWaitMs;
5333
5334 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005335 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5336 nullptr /* patchHandle */, requiresMuteCheck);
5337 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5338 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005339 return muteWaitMs;
5340 }
Eric Laurente552edb2014-03-10 17:42:56 -07005341
5342 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005343 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005344
François Gaffie11d30102018-11-02 16:09:09 +01005345 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5346 // output profile
5347 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5348 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5349 return 0;
5350 }
Eric Laurente552edb2014-03-10 17:42:56 -07005351
François Gaffie11d30102018-11-02 16:09:09 +01005352 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005353
François Gaffie11d30102018-11-02 16:09:09 +01005354 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5355
5356 if (!filteredDevices.isEmpty()) {
5357 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005358 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005359
5360 // if the outputs are not materially active, there is no need to mute.
5361 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005362 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005363 } else {
5364 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5365 muteWaitMs = 0;
5366 }
Eric Laurente552edb2014-03-10 17:42:56 -07005367
5368 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005369 // the requested device is AUDIO_DEVICE_NONE
5370 // OR the requested device is the same as current device
5371 // AND force is not specified
5372 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005373 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005374 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005375 !force && outputDesc->getPatchHandle() != 0) {
5376 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5377 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005378 return muteWaitMs;
5379 }
5380
François Gaffie11d30102018-11-02 16:09:09 +01005381 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005382
Eric Laurente552edb2014-03-10 17:42:56 -07005383 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005384 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005385 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005386 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005387 PatchBuilder patchBuilder;
5388 patchBuilder.addSource(outputDesc);
5389 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5390 for (const auto &filteredDevice : filteredDevices) {
5391 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005392 }
5393
François Gaffie11d30102018-11-02 16:09:09 +01005394 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005395 }
Eric Laurente552edb2014-03-10 17:42:56 -07005396
5397 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005398 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005399
5400 return muteWaitMs;
5401}
5402
Eric Laurentc75307b2015-03-17 15:29:32 -07005403status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 int delayMs,
5405 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005406{
Eric Laurent6a94d692014-05-20 11:18:06 -07005407 ssize_t index;
5408 if (patchHandle) {
5409 index = mAudioPatches.indexOfKey(*patchHandle);
5410 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005411 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005412 }
5413 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005414 return INVALID_OPERATION;
5415 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005416 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5417 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005418 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005419 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 removeAudioPatch(patchDesc->mHandle);
5421 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005422 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005423 return status;
5424}
5425
5426status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005427 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 bool force,
5429 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005430{
5431 status_t status = NO_ERROR;
5432
Eric Laurent1f2f2232014-06-02 12:01:23 -07005433 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005434 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5435 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005436
François Gaffie11d30102018-11-02 16:09:09 +01005437 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005438 PatchBuilder patchBuilder;
5439 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005440 // AUDIO_SOURCE_HOTWORD is for internal use only:
5441 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005442 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5443 auto result = usecase;
5444 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5445 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5446 }
5447 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005448 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005449 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005450 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005451 }
5452 }
5453 return status;
5454}
5455
Eric Laurent6a94d692014-05-20 11:18:06 -07005456status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5457 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005458{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005459 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 ssize_t index;
5461 if (patchHandle) {
5462 index = mAudioPatches.indexOfKey(*patchHandle);
5463 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005464 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 }
5466 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005467 return INVALID_OPERATION;
5468 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005469 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5470 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005471 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005472 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005473 removeAudioPatch(patchDesc->mHandle);
5474 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005475 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005476 return status;
5477}
5478
François Gaffie11d30102018-11-02 16:09:09 +01005479sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005480 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005481 audio_format_t& format,
5482 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005483 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005484{
5485 // Choose an input profile based on the requested capture parameters: select the first available
5486 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005487 //
5488 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5489 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005490
Glenn Kasten730b9262018-03-29 15:01:26 -07005491 sp<IOProfile> firstInexact;
5492 uint32_t updatedSamplingRate = 0;
5493 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5494 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005495 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005496 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005497 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005498 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005499 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005500 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005501 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005502 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005503 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005504 &channelMask /*updatedChannelMask*/,
5505 // FIXME ugly cast
5506 (audio_output_flags_t) flags,
5507 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005508 return profile;
5509 }
François Gaffie11d30102018-11-02 16:09:09 +01005510 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005511 samplingRate,
5512 &updatedSamplingRate,
5513 format,
5514 &updatedFormat,
5515 channelMask,
5516 &updatedChannelMask,
5517 // FIXME ugly cast
5518 (audio_output_flags_t) flags,
5519 false /*exactMatchRequiredForInputFlags*/)) {
5520 firstInexact = profile;
5521 }
5522
Eric Laurente552edb2014-03-10 17:42:56 -07005523 }
5524 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005525 if (firstInexact != nullptr) {
5526 samplingRate = updatedSamplingRate;
5527 format = updatedFormat;
5528 channelMask = updatedChannelMask;
5529 return firstInexact;
5530 }
Eric Laurente552edb2014-03-10 17:42:56 -07005531 return NULL;
5532}
5533
Francois Gaffie716e1432019-01-14 16:58:59 +01005534sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5535 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005536{
Eric Laurent97ac8712018-07-27 18:59:02 -07005537 // Honor explicit routing requests only if all active clients have a preferred route in which
5538 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005539 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005540 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005541 if (device != nullptr) {
5542 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005543 }
5544
François Gaffie11d30102018-11-02 16:09:09 +01005545 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005546 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005547 policyMix);
5548 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005549 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005550}
5551
Francois Gaffie716e1432019-01-14 16:58:59 +01005552sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005553{
Francois Gaffie716e1432019-01-14 16:58:59 +01005554 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5555 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5556 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5557 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005558 String8(attributes.tags + strlen("addr=")),
5559 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005560 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005561 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005562}
5563
Eric Laurente0720872014-03-11 09:30:41 -07005564float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005565 int index,
5566 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005567{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005568 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005569
5570 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5571 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5572 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5573 // the ringtone volume
5574 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5575 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5576 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5577 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5578 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5579 }
5580
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005581 // in-call: always cap volume by voice volume + some low headroom
5582 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005583 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005584 switch (stream) {
5585 case AUDIO_STREAM_SYSTEM:
5586 case AUDIO_STREAM_RING:
5587 case AUDIO_STREAM_MUSIC:
5588 case AUDIO_STREAM_ALARM:
5589 case AUDIO_STREAM_NOTIFICATION:
5590 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5591 case AUDIO_STREAM_DTMF:
5592 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005593 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005594 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005595 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005596 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005597 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005598 if (volumeDB > maxVoiceVolDb) {
5599 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5600 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5601 volumeDB = maxVoiceVolDb;
5602 }
5603 } break;
5604 default:
5605 break;
5606 }
5607 }
5608
Eric Laurente552edb2014-03-10 17:42:56 -07005609 // if a headset is connected, apply the following rules to ring tones and notifications
5610 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005611 // - always attenuate notifications volume by 6dB
5612 // - attenuate ring tones volume by 6dB unless music is not playing and
5613 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005614 // - if music is playing, always limit the volume to current music volume,
5615 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005616 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005617 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5618 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5619 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005620 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005621 AUDIO_DEVICE_OUT_USB_HEADSET |
5622 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005623 ((stream_strategy == STRATEGY_SONIFICATION)
5624 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005625 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005626 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005627 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005628 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005629 // when the phone is ringing we must consider that music could have been paused just before
5630 // by the music application and behave as if music was active if the last music track was
5631 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005632 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005633 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005634 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005635 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005636 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005637 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5638 musicDevice),
5639 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005640 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5641 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005642 if (volumeDB > minVolDB) {
5643 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005644 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005645 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005646 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5647 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5648 // on A2DP, also ensure notification volume is not too low compared to media when
5649 // intended to be played
5650 if ((volumeDB > -96.0f) &&
5651 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5652 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5653 stream, device,
5654 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5655 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5656 }
5657 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005658 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5659 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005660 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005661 }
5662 }
5663
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005664 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005665}
5666
Eric Laurent3839bc02018-07-10 18:33:34 -07005667int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5668 audio_stream_type_t srcStream,
5669 audio_stream_type_t dstStream)
5670{
5671 if (srcStream == dstStream) {
5672 return srcIndex;
5673 }
5674 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5675 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5676 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5677 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5678
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005679 // preserve mute request or correct range
5680 if (srcIndex < minSrc) {
5681 if (srcIndex == 0) {
5682 return 0;
5683 }
5684 srcIndex = minSrc;
5685 } else if (srcIndex > maxSrc) {
5686 srcIndex = maxSrc;
5687 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005688 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5689}
5690
Eric Laurente0720872014-03-11 09:30:41 -07005691status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005692 int index,
5693 const sp<AudioOutputDescriptor>& outputDesc,
5694 audio_devices_t device,
5695 int delayMs,
5696 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005697{
Eric Laurente552edb2014-03-10 17:42:56 -07005698 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005699 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005700 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005701 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005702 return NO_ERROR;
5703 }
François Gaffie2110e042015-03-24 08:41:51 +01005704 audio_policy_forced_cfg_t forceUseForComm =
5705 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005706 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005707 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5708 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005709 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005710 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005711 return INVALID_OPERATION;
5712 }
5713
Eric Laurentc75307b2015-03-17 15:29:32 -07005714 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005715 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005716 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005717
Eric Laurentffbc80f2015-03-18 18:30:19 -07005718 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005719 if (outputDesc->isFixedVolume(device) ||
5720 // Force VoIP volume to max for bluetooth SCO
5721 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5722 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005723 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005724 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005725
Eric Laurentffbc80f2015-03-18 18:30:19 -07005726 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005727
Eric Laurent3b73df72014-03-11 09:06:29 -07005728 if (stream == AUDIO_STREAM_VOICE_CALL ||
5729 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005730 float voiceVolume;
5731 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005732 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005733 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005734 } else {
5735 voiceVolume = 1.0;
5736 }
5737
Eric Laurent18fba842016-03-31 14:41:26 -07005738 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005739 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5740 mLastVoiceVolume = voiceVolume;
5741 }
5742 }
5743
5744 return NO_ERROR;
5745}
5746
Eric Laurentc75307b2015-03-17 15:29:32 -07005747void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5748 audio_devices_t device,
5749 int delayMs,
5750 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005751{
Eric Laurentc75307b2015-03-17 15:29:32 -07005752 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005753
Eric Laurent794fde22016-03-11 09:50:45 -08005754 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005755 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005756 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005757 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005758 device,
5759 delayMs,
5760 force);
5761 }
5762}
5763
Eric Laurente0720872014-03-11 09:30:41 -07005764void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005765 bool on,
5766 const sp<AudioOutputDescriptor>& outputDesc,
5767 int delayMs,
5768 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005769{
Eric Laurent72249d52015-06-08 11:12:15 -07005770 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5771 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005772 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005773 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005774 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005775 }
5776 }
5777}
5778
Eric Laurente0720872014-03-11 09:30:41 -07005779void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005780 bool on,
5781 const sp<AudioOutputDescriptor>& outputDesc,
5782 int delayMs,
5783 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005784{
Eric Laurente552edb2014-03-10 17:42:56 -07005785 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005786 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005787 }
5788
Eric Laurentc75307b2015-03-17 15:29:32 -07005789 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5790 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005791
5792 if (on) {
5793 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005794 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005795 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005796 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005797 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005798 }
5799 }
5800 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5801 outputDesc->mMuteCount[stream]++;
5802 } else {
5803 if (outputDesc->mMuteCount[stream] == 0) {
5804 ALOGV("setStreamMute() unmuting non muted stream!");
5805 return;
5806 }
5807 if (--outputDesc->mMuteCount[stream] == 0) {
5808 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005809 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005810 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005811 device,
5812 delayMs);
5813 }
5814 }
5815}
5816
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005817audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5818{
5819 // flags to stream type mapping
5820 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5821 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5822 }
5823 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5824 return AUDIO_STREAM_BLUETOOTH_SCO;
5825 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005826 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5827 return AUDIO_STREAM_TTS;
5828 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005829
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005830 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005831}
Eric Laurente83b55d2014-11-14 10:06:21 -08005832
François Gaffie53615e22015-03-19 09:24:12 +01005833bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5834{
Eric Laurente83b55d2014-11-14 10:06:21 -08005835 // has flags that map to a strategy?
5836 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5837 return true;
5838 }
5839
5840 // has known usage?
5841 switch (paa->usage) {
5842 case AUDIO_USAGE_UNKNOWN:
5843 case AUDIO_USAGE_MEDIA:
5844 case AUDIO_USAGE_VOICE_COMMUNICATION:
5845 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5846 case AUDIO_USAGE_ALARM:
5847 case AUDIO_USAGE_NOTIFICATION:
5848 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5849 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5850 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5851 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5852 case AUDIO_USAGE_NOTIFICATION_EVENT:
5853 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5854 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5855 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5856 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005857 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005858 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005859 break;
5860 default:
5861 return false;
5862 }
5863 return true;
5864}
5865
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005866bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005867 routing_strategy strategy, uint32_t inPastMs,
5868 nsecs_t sysTime) const
5869{
5870 if ((sysTime == 0) && (inPastMs != 0)) {
5871 sysTime = systemTime();
5872 }
Eric Laurent794fde22016-03-11 09:50:45 -08005873 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005874 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005875 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005876 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5877 return true;
5878 }
5879 }
5880 return false;
5881}
5882
François Gaffie11d30102018-11-02 16:09:09 +01005883bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5884 routing_strategy strategy, uint32_t inPastMs,
5885 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005886{
5887 for (size_t i = 0; i < mOutputs.size(); i++) {
5888 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5889 if (outputDesc->sharesHwModuleWith(desc)
5890 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5891 return true;
5892 }
5893 }
5894 return false;
5895}
5896
François Gaffie2110e042015-03-24 08:41:51 +01005897audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5898{
5899 return mEngine->getForceUse(usage);
5900}
5901
5902bool AudioPolicyManager::isInCall()
5903{
5904 return isStateInCall(mEngine->getPhoneState());
5905}
5906
5907bool AudioPolicyManager::isStateInCall(int state)
5908{
5909 return is_state_in_call(state);
5910}
5911
Eric Laurentd60560a2015-04-10 11:31:20 -07005912void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5913{
5914 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005915 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5916 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5917 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5918 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005919 }
5920 }
5921
5922 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5923 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5924 bool release = false;
5925 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5926 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5927 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5928 source->ext.device.type == deviceDesc->type()) {
5929 release = true;
5930 }
5931 }
5932 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5933 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5934 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5935 sink->ext.device.type == deviceDesc->type()) {
5936 release = true;
5937 }
5938 }
5939 if (release) {
5940 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5941 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5942 }
5943 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005944
5945 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005946}
5947
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005948void AudioPolicyManager::modifySurroundFormats(
5949 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005950 std::unordered_set<audio_format_t> enforcedSurround(
5951 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005952 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5953 for (const auto& pair : mConfig.getSurroundFormats()) {
5954 allSurround.insert(pair.first);
5955 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5956 }
Phil Burk09bc4612016-02-24 15:58:15 -08005957
5958 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5959 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005960 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005961 // This is the resulting set of formats depending on the surround mode:
5962 // 'all surround' = allSurround
5963 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5964 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5965 // 'manual surround' = mManualSurroundFormats
5966 // AUTO: formats v 'enforced surround'
5967 // ALWAYS: formats v 'all surround' v 'enforced surround'
5968 // NEVER: formats ^ 'non-surround'
5969 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005970
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005971 std::unordered_set<audio_format_t> formatSet;
5972 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5973 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005974 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005975 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005976 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005977 formatSet.insert(*formatIter);
5978 }
5979 }
5980 } else {
5981 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5982 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005983 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005984
jiabin81772902018-04-02 17:52:27 -07005985 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005986 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005987 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5988 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5989 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005990 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005991 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5992 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5993 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005994 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005995 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005996 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005997 for (const auto& format : formatSet) {
5998 formatsPtr->push(format);
5999 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006000}
6001
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006002void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006003 ChannelsVector &channelMasks = *channelMasksPtr;
6004 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6005 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6006
6007 // If NEVER, then remove support for channelMasks > stereo.
6008 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6009 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6010 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6011 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6012 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6013 channelMasks.removeAt(maskIndex);
6014 } else {
6015 maskIndex++;
6016 }
6017 }
jiabin81772902018-04-02 17:52:27 -07006018 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6019 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6020 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006021 bool supports5dot1 = false;
6022 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006023 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006024 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6025 supports5dot1 = true;
6026 break;
6027 }
6028 }
6029 // If not then add 5.1 support.
6030 if (!supports5dot1) {
6031 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006032 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006033 }
Phil Burk09bc4612016-02-24 15:58:15 -08006034 }
6035}
6036
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006037void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006038 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006039 AudioProfileVector &profiles)
6040{
6041 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006042 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006043
François Gaffie112b0af2015-11-19 16:13:25 +01006044 // Format MUST be checked first to update the list of AudioProfile
6045 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006046 reply = mpClientInterface->getParameters(
6047 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006048 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006049 AudioParameter repliedParameters(reply);
6050 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006051 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006052 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6053 return;
6054 }
Phil Burk09bc4612016-02-24 15:58:15 -08006055 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006056 if (device == AUDIO_DEVICE_OUT_HDMI
6057 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006058 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006059 }
Phil Burk09bc4612016-02-24 15:58:15 -08006060 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006061 }
François Gaffie112b0af2015-11-19 16:13:25 +01006062
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006063 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006064 ChannelsVector channelMasks;
6065 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006066 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006067 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006068
6069 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006070 reply = mpClientInterface->getParameters(
6071 ioHandle,
6072 requestedParameters.toString() + ";" +
6073 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006074 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006075 AudioParameter repliedParameters(reply);
6076 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006077 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006078 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006079 }
6080 }
6081 if (profiles.hasDynamicChannelsFor(format)) {
6082 reply = mpClientInterface->getParameters(ioHandle,
6083 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006084 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006085 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006086 AudioParameter repliedParameters(reply);
6087 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006088 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006089 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006090 if (device == AUDIO_DEVICE_OUT_HDMI
6091 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006092 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006093 }
François Gaffie112b0af2015-11-19 16:13:25 +01006094 }
6095 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006096 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006097 }
6098}
Eric Laurentd60560a2015-04-10 11:31:20 -07006099
Mikhail Naganovdc769682018-05-04 15:34:08 -07006100status_t AudioPolicyManager::installPatch(const char *caller,
6101 audio_patch_handle_t *patchHandle,
6102 AudioIODescriptorInterface *ioDescriptor,
6103 const struct audio_patch *patch,
6104 int delayMs)
6105{
6106 ssize_t index = mAudioPatches.indexOfKey(
6107 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6108 *patchHandle : ioDescriptor->getPatchHandle());
6109 sp<AudioPatch> patchDesc;
6110 status_t status = installPatch(
6111 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6112 if (status == NO_ERROR) {
6113 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6114 }
6115 return status;
6116}
6117
6118status_t AudioPolicyManager::installPatch(const char *caller,
6119 ssize_t index,
6120 audio_patch_handle_t *patchHandle,
6121 const struct audio_patch *patch,
6122 int delayMs,
6123 uid_t uid,
6124 sp<AudioPatch> *patchDescPtr)
6125{
6126 sp<AudioPatch> patchDesc;
6127 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6128 if (index >= 0) {
6129 patchDesc = mAudioPatches.valueAt(index);
6130 afPatchHandle = patchDesc->mAfPatchHandle;
6131 }
6132
6133 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6134 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6135 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6136 if (status == NO_ERROR) {
6137 if (index < 0) {
6138 patchDesc = new AudioPatch(patch, uid);
6139 addAudioPatch(patchDesc->mHandle, patchDesc);
6140 } else {
6141 patchDesc->mPatch = *patch;
6142 }
6143 patchDesc->mAfPatchHandle = afPatchHandle;
6144 if (patchHandle) {
6145 *patchHandle = patchDesc->mHandle;
6146 }
6147 nextAudioPortGeneration();
6148 mpClientInterface->onAudioPatchListUpdate();
6149 }
6150 if (patchDescPtr) *patchDescPtr = patchDesc;
6151 return status;
6152}
6153
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006154} // namespace android