blob: cc151e7d8a2a2daf3735f85b15c10a9a32782e4d [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;
Eric Laurentdc462862016-07-19 12:29:53 -0700489 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700490
François Gaffie11d30102018-11-02 16:09:09 +0100491 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700492 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700493 }
François Gaffie11d30102018-11-02 16:09:09 +0100494 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
495
Francois Gaffie716e1432019-01-14 16:58:59 +0100496 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
497 auto txDevice = getDeviceAndMixForAttributes(attr);
François Gaffie11d30102018-11-02 16:09:09 +0100498 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
499 rxDevices.toString().c_str(), txDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700500
501 // release existing RX patch if any
502 if (mCallRxPatch != 0) {
503 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
504 mCallRxPatch.clear();
505 }
506 // release TX patch if any
507 if (mCallTxPatch != 0) {
508 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
509 mCallTxPatch.clear();
510 }
511
512 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
513 // via setOutputDevice() on primary output.
514 // Otherwise, create two audio patches for TX and RX path.
François Gaffie11d30102018-11-02 16:09:09 +0100515 if (availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) {
516 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 // If the TX device is also on the primary HW module, setOutputDevice() will take care
518 // of it due to legacy implementation. If not, create a patch.
François Gaffie11d30102018-11-02 16:09:09 +0100519 if (!availablePrimaryModuleInputDevices().contains(txDevice)) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700520 createTxPatch = true;
521 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700522 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100523 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700524 createTxPatch = true;
525 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700526 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
528 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700529
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800530 return muteWaitMs;
531}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700532
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100534 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700535 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536
François Gaffie11d30102018-11-02 16:09:09 +0100537 if (device == nullptr) {
538 return nullptr;
539 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800540 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100541 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 addSource(mAvailableInputDevices.getDevice(
543 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800544 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100545 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800546 addSink(mAvailableOutputDevices.getDevice(
547 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800548 }
549
François Gaffie11d30102018-11-02 16:09:09 +0100550 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
551 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 device : mAvailableOutputDevices.getDevice(
553 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100554 SortedVector<audio_io_handle_t> outputs =
555 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
556 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800557 // request to reuse existing output stream if one is already opened to reach the target device
558 if (output != AUDIO_IO_HANDLE_NONE) {
559 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100560 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
561 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700562 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800563 }
564
565 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700566 // terminate active capture if on the same HW module as the call TX source device
567 // FIXME: would be better to refine to only inputs whose profile connects to the
568 // call TX device but this information is not in the audio patch and logic here must be
569 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800570 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100571 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700572 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700573 }
574 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700575 }
Eric Laurentdc462862016-07-19 12:29:53 -0700576
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800577 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700578 status_t status = mpClientInterface->createAudioPatch(
579 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800580 ALOGW_IF(status != NO_ERROR,
581 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
582 sp<AudioPatch> audioPatch;
583 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700584 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800585 audioPatch->mAfPatchHandle = afPatchHandle;
586 audioPatch->mUid = mUidCached;
587 }
588 return audioPatch;
589}
590
Mikhail Naganovdc769682018-05-04 15:34:08 -0700591sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100592 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700593 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800594 ALOG_ASSERT(!deviceList.isEmpty(),
595 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700596 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700597}
598
Mikhail Naganov100f0122018-11-29 11:22:16 -0800599audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
600 const DeviceVector& devices, const char *moduleId) const {
601 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
602 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
603}
604
605bool AudioPolicyManager::isDeviceOfModule(
606 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
607 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
608 if (module != 0) {
609 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
610 .indexOf(devDesc) != NAME_NOT_FOUND
611 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
612 .indexOf(devDesc) != NAME_NOT_FOUND;
613 }
614 return false;
615}
616
Eric Laurente0720872014-03-11 09:30:41 -0700617void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700618{
619 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100620 // store previous phone state for management of sonification strategy below
621 int oldState = mEngine->getPhoneState();
622
623 if (mEngine->setPhoneState(state) != NO_ERROR) {
624 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700625 return;
626 }
François Gaffie2110e042015-03-24 08:41:51 +0100627 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700628 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700629 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700630 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800631 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700632 }
633
François Gaffie2110e042015-03-24 08:41:51 +0100634 /**
635 * Switching to or from incall state or switching between telephony and VoIP lead to force
636 * routing command.
637 */
638 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
639 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700640
641 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700642 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700643
Eric Laurente552edb2014-03-10 17:42:56 -0700644 int delayMs = 0;
645 if (isStateInCall(state)) {
646 nsecs_t sysTime = systemTime();
647 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700648 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700649 // mute media and sonification strategies and delay device switch by the largest
650 // latency of any output where either strategy is active.
651 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100652 if ((isStrategyActive(desc, STRATEGY_MEDIA,
653 SONIFICATION_HEADSET_MUSIC_DELAY,
654 sysTime) ||
655 isStrategyActive(desc, STRATEGY_SONIFICATION,
656 SONIFICATION_HEADSET_MUSIC_DELAY,
657 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700658 (delayMs < (int)desc->latency()*2)) {
659 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700660 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700661 setStrategyMute(STRATEGY_MEDIA, true, desc);
662 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700663 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700664 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
665 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700666 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
667 }
668 }
669
Eric Laurent87ffa392015-05-22 10:32:38 -0700670 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100671 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700672 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100673 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700674 // force routing command to audio hardware when ending call
675 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100676 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
677 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679
Eric Laurent87ffa392015-05-22 10:32:38 -0700680 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100681 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 } else if (oldState == AUDIO_MODE_IN_CALL) {
683 if (mCallRxPatch != 0) {
684 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
685 mCallRxPatch.clear();
686 }
687 if (mCallTxPatch != 0) {
688 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
689 mCallTxPatch.clear();
690 }
François Gaffie11d30102018-11-02 16:09:09 +0100691 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700692 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100693 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700694 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700696
697 // reevaluate routing on all outputs in case tracks have been started during the call
698 for (size_t i = 0; i < mOutputs.size(); i++) {
699 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100700 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700701 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100702 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700703 }
704 }
705
Eric Laurente552edb2014-03-10 17:42:56 -0700706 if (isStateInCall(state)) {
707 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700708 // force reevaluating accessibility routing when call starts
709 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700710 }
711
712 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700713 if (state == AUDIO_MODE_RINGTONE &&
714 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700715 mLimitRingtoneVolume = true;
716 } else {
717 mLimitRingtoneVolume = false;
718 }
719}
720
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700721audio_mode_t AudioPolicyManager::getPhoneState() {
722 return mEngine->getPhoneState();
723}
724
Eric Laurente0720872014-03-11 09:30:41 -0700725void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100726 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700727{
François Gaffie2110e042015-03-24 08:41:51 +0100728 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700729 if (config == mEngine->getForceUse(usage)) {
730 return;
731 }
Eric Laurente552edb2014-03-10 17:42:56 -0700732
François Gaffie2110e042015-03-24 08:41:51 +0100733 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
734 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
735 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700736 }
François Gaffie2110e042015-03-24 08:41:51 +0100737 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
738 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
739 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700740
741 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700742 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800743
Eric Laurentdc462862016-07-19 12:29:53 -0700744 //FIXME: workaround for truncated touch sounds
745 // to be removed when the problem is handled by system UI
746 uint32_t delayMs = 0;
747 uint32_t waitMs = 0;
748 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
749 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
750 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700751 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100752 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
753 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700754 }
Eric Laurente552edb2014-03-10 17:42:56 -0700755 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700756 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100757 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700758 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100759 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 }
François Gaffie11d30102018-11-02 16:09:09 +0100761 if (forceVolumeReeval && !newDevices.isEmpty()) {
762 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 }
764 }
765
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800766 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100767 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700768 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100769 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800770 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700771 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800772 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700773 }
Eric Laurente552edb2014-03-10 17:42:56 -0700774 }
Eric Laurente552edb2014-03-10 17:42:56 -0700775}
776
Eric Laurente0720872014-03-11 09:30:41 -0700777void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700778{
779 ALOGV("setSystemProperty() property %s, value %s", property, value);
780}
781
Michael Chana94fbb22018-04-24 14:31:19 +1000782// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
783// search to profiles for direct outputs.
784sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100785 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000786 uint32_t samplingRate,
787 audio_format_t format,
788 audio_channel_mask_t channelMask,
789 audio_output_flags_t flags,
790 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700791{
Michael Chana94fbb22018-04-24 14:31:19 +1000792 if (directOnly) {
793 // only retain flags that will drive the direct output profile selection
794 // if explicitly requested
795 static const uint32_t kRelevantFlags =
796 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
797 AUDIO_OUTPUT_FLAG_VOIP_RX);
798 flags =
799 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
800 }
Eric Laurent861a6282015-05-18 15:40:16 -0700801
802 sp<IOProfile> profile;
803
Mikhail Naganovd4120142017-12-06 15:49:22 -0800804 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100806 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700807 samplingRate, NULL /*updatedSamplingRate*/,
808 format, NULL /*updatedFormat*/,
809 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700810 flags)) {
811 continue;
812 }
813 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100814 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700815 continue;
816 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800817 // reject profiles if connected device does not support codec
818 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
819 continue;
820 }
Michael Chana94fbb22018-04-24 14:31:19 +1000821 if (!directOnly) return curProfile;
822 // when searching for direct outputs, if several profiles are compatible, give priority
823 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100824 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700825 continue;
826 }
827 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100828 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700829 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700830 }
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832 }
Eric Laurent861a6282015-05-18 15:40:16 -0700833 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700834}
835
Eric Laurentf4e63452017-11-06 19:31:46 +0000836audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700837{
Eric Laurent3b73df72014-03-11 09:06:29 -0700838 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100839 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800840
841 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
842 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
843 // format, flags, etc. This may result in some discrepancy for functions that utilize
844 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
845 // and AudioSystem::getOutputSamplingRate().
846
François Gaffie11d30102018-11-02 16:09:09 +0100847 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
848 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700849
François Gaffie11d30102018-11-02 16:09:09 +0100850 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
851 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000852 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700853}
854
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700855status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
856 const audio_attributes_t *srcAttr,
857 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700859 if (srcAttr != NULL) {
860 if (!isValidAttributes(srcAttr)) {
861 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
862 __func__,
863 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
864 srcAttr->tags);
865 return BAD_VALUE;
866 }
867 *dstAttr = *srcAttr;
868 } else {
869 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
870 ALOGE("%s: invalid stream type", __func__);
871 return BAD_VALUE;
872 }
873 stream_type_to_audio_attributes(srcStream, dstAttr);
874 }
875 return NO_ERROR;
876}
877
878status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
879 audio_io_handle_t *output,
880 audio_session_t session,
881 const audio_attributes_t *attr,
882 audio_stream_type_t *stream,
883 uid_t uid,
884 const audio_config_t *config,
885 audio_output_flags_t *flags,
886 audio_port_handle_t *selectedDeviceId)
887{
François Gaffie11d30102018-11-02 16:09:09 +0100888 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700889 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100890 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100891 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100892 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700893
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700894 status_t status = getAudioAttributes(resultAttr, attr, *stream);
895 if (status != NO_ERROR) {
896 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700897 }
898
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700899 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700900 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700901 __func__,
902 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100903 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700904
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700905 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700906
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700907 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700908
Scott Randolph7b1fd232018-06-18 15:33:03 -0700909 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100910 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
911 if (requestedDevice != nullptr) {
912 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700913 } else {
914 // If no explict route, is there a matching dynamic policy that applies?
915 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700916 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700917 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
918 if (!audio_has_proportional_frames(config->format)) {
919 return BAD_VALUE;
920 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700921 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700922 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700923 AudioMix *mix = desc->mPolicyMix;
924 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800925 mAvailableOutputDevices.getDevice(
926 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700927 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 ALOGV("%s returns output %d", __func__, *output);
929 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700930 }
931
932 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700933 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
934 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700935 return BAD_VALUE;
936 }
François Gaffie11d30102018-11-02 16:09:09 +0100937 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700938 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700939
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700940 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200941 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700942 }
943
Nadav Barb2f18162018-07-18 13:01:53 +0300944 // Set incall music only if device was explicitly set, and fallback to the device which is
945 // chosen by the engine if not.
946 // FIXME: provide a more generic approach which is not device specific and move this back
947 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200948 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100949 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300951 audio_is_linear_pcm(config->format) &&
952 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100953 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300954 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
955 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700956 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100957 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300958 }
959 }
960
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700961 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800962 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100963 __func__,
964 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700965
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100966 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100967 if (!msdDevices.isEmpty()) {
968 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800969 sp<DeviceDescriptor> deviceDesc =
970 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100971 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
972 ALOGV("%s() Using MSD devices %s instead of device %s",
973 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
974 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100975 } else {
976 *output = AUDIO_IO_HANDLE_NONE;
977 }
978 }
François Gaffie11d30102018-11-02 16:09:09 +0100979 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100980 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +0100981 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100982 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800983 if (*output == AUDIO_IO_HANDLE_NONE) {
984 return INVALID_OPERATION;
985 }
Paul McLeanaa981192015-03-21 09:55:15 -0700986
François Gaffie11d30102018-11-02 16:09:09 +0100987 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700988
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700989 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
990
991 return NO_ERROR;
992}
993
994status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
995 audio_io_handle_t *output,
996 audio_session_t session,
997 audio_stream_type_t *stream,
998 uid_t uid,
999 const audio_config_t *config,
1000 audio_output_flags_t *flags,
1001 audio_port_handle_t *selectedDeviceId,
1002 audio_port_handle_t *portId)
1003{
1004 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1005 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1006 return INVALID_OPERATION;
1007 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001008 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001009 audio_attributes_t resultAttr;
1010 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1011 config, flags, selectedDeviceId);
1012 if (status != NO_ERROR) {
1013 return status;
1014 }
1015
Eric Laurent8fc147b2018-07-22 19:13:55 -07001016 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1017 .format = config->format,
1018 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001019 *portId = AudioPort::getNextUniqueId();
1020
Eric Laurent8fc147b2018-07-22 19:13:55 -07001021 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001022 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001023 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001024 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -07001025 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001026 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001027 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001028
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001029 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +01001030 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001031
Eric Laurente83b55d2014-11-14 10:06:21 -08001032 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001033}
1034
François Gaffie11d30102018-11-02 16:09:09 +01001035audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1036 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001037 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001038 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001039 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001040 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001041{
Andy Hungc88b0642018-04-27 15:42:35 -07001042 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001043 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001044
Eric Laurente552edb2014-03-10 17:42:56 -07001045 // open a direct output if required by specified parameters
1046 //force direct flag if offload flag is set: offloading implies a direct output stream
1047 // and all common behaviors are driven by checking only the direct flag
1048 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001049 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1050 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 }
Nadav Bar766fb022018-01-07 12:18:03 +02001052 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1053 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001054 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001055 // only allow deep buffering for music stream type
1056 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001057 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001058 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001059 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001060 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1061 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001062 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001063 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001064 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001065 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001066 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001067 audio_is_linear_pcm(config->format) &&
1068 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001069 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001070 AUDIO_OUTPUT_FLAG_DIRECT);
1071 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001072 }
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Nadav Bar766fb022018-01-07 12:18:03 +02001074
Eric Laurentb732cf52014-09-24 19:08:21 -07001075 sp<IOProfile> profile;
1076
1077 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001078 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001079 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001080 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1081 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001082 goto non_direct_output;
1083 }
1084
Andy Hung2ddee192015-12-18 17:34:44 -08001085 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1086 // This prevents creating an offloaded track and tearing it down immediately after start
1087 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001088 // FIXME: We should check the audio session here but we do not have it in this context.
1089 // This may prevent offloading in rare situations where effects are left active by apps
1090 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001091
Nadav Bar766fb022018-01-07 12:18:03 +02001092 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001093 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001094 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001095 config->sample_rate,
1096 config->format,
1097 config->channel_mask,
1098 (audio_output_flags_t)*flags,
1099 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001100 }
1101
Eric Laurent1c333e22014-05-20 10:48:17 -07001102 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001103 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1104 for (size_t i = 0; i < mOutputs.size(); i++) {
1105 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1106 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1107 // reuse direct output if currently open by the same client
1108 // and configured with same parameters
1109 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001110 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001111 (config->channel_mask == desc->mChannelMask) &&
1112 (session == desc->mDirectClientSession)) {
1113 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001114 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001115 mOutputs.keyAt(i), session);
1116 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001117 }
1118 }
1119 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001120
1121 if (!profile->canOpenNewIo()) {
1122 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001123 }
Eric Laurent861a6282015-05-18 15:40:16 -07001124
Eric Laurent3974e3b2017-12-07 17:58:43 -08001125 sp<SwAudioOutputDescriptor> outputDesc =
1126 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001127
François Gaffie11d30102018-11-02 16:09:09 +01001128 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001129
Dean Wheatley3023b382018-08-09 07:42:40 +10001130 // MSD patch may be using the only output stream that can service this request. Release
1131 // MSD patch to prioritize this request over any active output on MSD.
1132 AudioPatchCollection msdPatches = getMsdPatches();
1133 for (size_t i = 0; i < msdPatches.size(); i++) {
1134 const auto& patch = msdPatches[i];
1135 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1136 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1137 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001138 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001139 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1140 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1141 releaseAudioPatch(patch->mHandle, mUidCached);
1142 break;
1143 }
1144 }
1145 }
1146
François Gaffie11d30102018-11-02 16:09:09 +01001147 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001148
1149 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001150 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001151 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001152 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001153 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001154 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1155 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001156 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1157 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001158 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001159 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001161 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001162 if (audio_is_linear_pcm(config->format) &&
1163 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001164 goto non_direct_output;
1165 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001166 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001167 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001168 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001169 outputDesc->mDirectClientSession = session;
1170
Eric Laurente552edb2014-03-10 17:42:56 -07001171 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001172 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001173 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001174 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001175 return output;
1176 }
1177
Eric Laurentb732cf52014-09-24 19:08:21 -07001178non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001179
1180 // A request for HW A/V sync cannot fallback to a mixed output because time
1181 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001182 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001183 return AUDIO_IO_HANDLE_NONE;
1184 }
1185
Eric Laurente552edb2014-03-10 17:42:56 -07001186 // ignoring channel mask due to downmix capability in mixer
1187
1188 // open a non direct output
1189
1190 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001191 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001192 // get which output is suitable for the specified stream. The actual
1193 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001194 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001195
Eric Laurent8838a382014-09-08 16:44:28 -07001196 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001197 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001198 output = selectOutput(outputs, *flags, config->format,
1199 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001200 }
François Gaffie11d30102018-11-02 16:09:09 +01001201 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001202 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001203 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001204
Eric Laurente552edb2014-03-10 17:42:56 -07001205 return output;
1206}
1207
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001208sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001209 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1210 mAvailableInputDevices);
1211 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1212}
1213
1214DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1215 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1216 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001217}
1218
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001219const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1220 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001221 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1222 if (msdModule != 0) {
1223 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1224 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1225 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1226 const struct audio_port_config *source = &patch->mPatch.sources[j];
1227 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1228 source->ext.device.hw_module == msdModule->getHandle()) {
1229 msdPatches.addAudioPatch(patch->mHandle, patch);
1230 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001231 }
1232 }
1233 }
1234 return msdPatches;
1235}
1236
François Gaffie11d30102018-11-02 16:09:09 +01001237status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001238 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1239{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001240 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001241 if (msdModule == nullptr) {
1242 ALOGE("%s() unable to get MSD module", __func__);
1243 return NO_INIT;
1244 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001245 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001246 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001247 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001248 return NO_INIT;
1249 }
1250 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1251 if (inputProfiles.isEmpty()) {
1252 ALOGE("%s() no input profiles for MSD module", __func__);
1253 return NO_INIT;
1254 }
1255 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1256 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001257 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001258 return NO_INIT;
1259 }
1260 AudioProfileVector msdProfiles;
1261 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1262 for (const auto &inProfile : inputProfiles) {
1263 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1264 msdProfiles.appendVector(inProfile->getAudioProfiles());
1265 }
1266 }
1267 AudioProfileVector deviceProfiles;
1268 for (const auto &outProfile : outputProfiles) {
1269 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1270 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1271 }
1272 }
1273 struct audio_config_base bestSinkConfig;
1274 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1275 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1276 &bestSinkConfig);
1277 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001278 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1279 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001280 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 }
1282 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1283 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1284 sinkConfig->format = bestSinkConfig.format;
1285 // For encoded streams force direct flag to prevent downstream mixing.
1286 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1287 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1288 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1289 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1290 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1291 sourceConfig->format = bestSinkConfig.format;
1292 // Copy input stream directly without any processing (e.g. resampling).
1293 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1294 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1295 if (hwAvSync) {
1296 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1297 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1298 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1299 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1300 }
1301 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1302 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1303 sinkConfig->config_mask |= config_mask;
1304 sourceConfig->config_mask |= config_mask;
1305 return NO_ERROR;
1306}
1307
François Gaffie11d30102018-11-02 16:09:09 +01001308PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001309{
1310 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001311 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001312 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1313 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1314 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1315 // For now, we just forcefully try with HwAvSync first.
1316 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1317 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1318 getBestMsdAudioProfileFor(
1319 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1320 if (res == NO_ERROR) {
1321 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1322 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1323 }
1324 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1325 " supporting PCM format conversion.", __func__);
1326 return patchBuilder;
1327}
1328
François Gaffie11d30102018-11-02 16:09:09 +01001329status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1330 sp<DeviceDescriptor> device = outputDevice;
1331 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001332 // Use media strategy for unspecified output device. This should only
1333 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1334 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001335 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1336 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1337 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001338 }
François Gaffie11d30102018-11-02 16:09:09 +01001339 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1340 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001341 const struct audio_patch* patch = patchBuilder.patch();
1342 const AudioPatchCollection msdPatches = getMsdPatches();
1343 if (!msdPatches.isEmpty()) {
1344 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1345 "The current MSD prototype only supports one output patch");
1346 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1347 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1348 return NO_ERROR;
1349 }
1350 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1351 }
1352 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1353 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1354 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1355 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001356 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1357 device->toString().c_str(), patch->sources[0].format,
1358 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001359 return status;
1360}
1361
Eric Laurente0720872014-03-11 09:30:41 -07001362audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001363 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001364 audio_format_t format,
1365 audio_channel_mask_t channelMask,
1366 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001367{
1368 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001369 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001370 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001371 // 1: the output supporting haptic playback when requesting haptic playback
1372 // 2: the output with the highest number of requested policy flags
1373 // 3: the output with the bit depth the closest to the requested one
1374 // 4: the primary output
1375 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001376
1377 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001378 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001379 }
1380 if (outputs.size() == 1) {
1381 return outputs[0];
1382 }
1383
1384 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001385 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1386 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001387 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1388 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1389 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001390 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1391 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001392
Eric Laurente78b6762018-12-19 16:29:01 -08001393 // Flags which must be present on both the request and the selected output
1394 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1395 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1396
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001397 for (audio_io_handle_t output : outputs) {
1398 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001399 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001400 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1401 continue;
1402 }
jiabin40573322018-11-08 12:08:02 -08001403 // If haptic channel is specified, use the haptic output if present.
1404 // When using haptic output, same audio format and sample rate are required.
1405 if (hapticChannelCount > 0) {
1406 // If haptic channel is specified, use the first output that
1407 // support haptic playback.
1408 if (audio_channel_count_from_out_mask(
1409 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1410 && format == outputDesc->mFormat
1411 && samplingRate == outputDesc->mSamplingRate) {
1412 return output;
1413 }
1414 } else {
1415 // When haptic channel is not specified, skip haptic output.
1416 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1417 continue;
1418 }
1419 }
Eric Laurente78b6762018-12-19 16:29:01 -08001420 if ((kMandatedFlags & flags) !=
1421 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1422 continue;
1423 }
jiabin40573322018-11-08 12:08:02 -08001424
Eric Laurent8838a382014-09-08 16:44:28 -07001425 // if a valid format is specified, skip output if not compatible
1426 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001427 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001428 continue;
1429 }
Eric Laurente6930022016-02-11 10:20:40 -08001430 if (AudioPort::isBetterFormatMatch(
1431 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001432 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001433 bestFormat = outputDesc->mFormat;
1434 }
Eric Laurent8838a382014-09-08 16:44:28 -07001435 }
1436
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001437 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001438 if (commonFlags >= maxCommonFlags) {
1439 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001440 if (format != AUDIO_FORMAT_INVALID
1441 && AudioPort::isBetterFormatMatch(
1442 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001443 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001444 bestFormatForFlags = outputDesc->mFormat;
1445 }
1446 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001447 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001448 maxCommonFlags = commonFlags;
1449 bestFormatForFlags = outputDesc->mFormat;
1450 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001451 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001452 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001453 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001454 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
1457 }
1458
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001459 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001460 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001461 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001462 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001463 return outputForFormat;
1464 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001465 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001466 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001467 }
1468
1469 return outputs[0];
1470}
1471
Eric Laurent8fc147b2018-07-22 19:13:55 -07001472status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001473{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001474 ALOGV("%s portId %d", __FUNCTION__, portId);
1475
1476 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1477 if (outputDesc == 0) {
1478 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001479 return BAD_VALUE;
1480 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001481 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001482
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001484 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001485
Eric Laurent733ce942017-12-07 12:18:25 -08001486 status_t status = outputDesc->start();
1487 if (status != NO_ERROR) {
1488 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001489 }
1490
Eric Laurent97ac8712018-07-27 18:59:02 -07001491 uint32_t delayMs;
1492 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001493
1494 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001495 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001496 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001497 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001498 if (delayMs != 0) {
1499 usleep(delayMs * 1000);
1500 }
1501
1502 return status;
1503}
1504
Eric Laurent97ac8712018-07-27 18:59:02 -07001505status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1506 const sp<TrackClientDescriptor>& client,
1507 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001508{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001509 // cannot start playback of STREAM_TTS if any other output is being used
1510 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001511
1512 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001513 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001514 if (stream == AUDIO_STREAM_TTS) {
1515 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001516 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001517 return INVALID_OPERATION;
1518 } else {
1519 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1520 }
1521 } else {
1522 // some playback other than beacon starts
1523 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1524 }
1525
Eric Laurent77305a62016-07-25 16:39:22 -07001526 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001527 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001528 bool force = !outputDesc->isActive() &&
1529 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001530
François Gaffie11d30102018-11-02 16:09:09 +01001531 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001532 AudioMix *policyMix = NULL;
1533 const char *address = NULL;
1534 if (outputDesc->mPolicyMix != NULL) {
1535 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001536 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001537 address = policyMix->mDeviceAddress.string();
1538 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001539 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001540 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001541 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001542 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001543 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1544 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001545 }
1546
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001547 // requiresMuteCheck is false when we can bypass mute strategy.
1548 // It covers a common case when there is no materially active audio
1549 // and muting would result in unnecessary delay and dropped audio.
1550 const uint32_t outputLatencyMs = outputDesc->latency();
1551 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1552
Eric Laurente552edb2014-03-10 17:42:56 -07001553 // increment usage count for this stream on the requested output:
1554 // NOTE that the usage count is the same for duplicated output and hardware output which is
1555 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001556 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001557
1558 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001559 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1560 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001561 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1562 }
1563 }
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurent36829f92017-04-07 19:04:42 -07001565 if (stream == AUDIO_STREAM_MUSIC) {
1566 selectOutputForMusicEffects();
1567 }
1568
François Gaffie11d30102018-11-02 16:09:09 +01001569 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001570 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001571 if (devices.isEmpty()) {
1572 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 }
Eric Laurent36829f92017-04-07 19:04:42 -07001574
Eric Laurente552edb2014-03-10 17:42:56 -07001575 routing_strategy strategy = getStrategy(stream);
1576 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001577 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1578 (beaconMuteLatency > 0);
1579 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001580 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001581 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001582 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001583 // An output has a shared device if
1584 // - managed by the same hw module
1585 // - supports the currently selected device
1586 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001587 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001588
Eric Laurent77305a62016-07-25 16:39:22 -07001589 // force a device change if any other output is:
1590 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001591 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001592 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001593 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001594 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001595 // change the device currently selected by the other output.
1596 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001597 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001598 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001599 force = true;
1600 }
1601 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001602 // a notification so that audio focus effect can propagate, or that a mute/unmute
1603 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001604 const uint32_t latencyMs = desc->latency();
1605 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1606
1607 if (shouldWait && isActive && (waitMs < latencyMs)) {
1608 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001609 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001610
1611 // Require mute check if another output is on a shared device
1612 // and currently active to have proper drain and avoid pops.
1613 // Note restoring AudioTracks onto this output needs to invoke
1614 // a volume ramp if there is no mute.
1615 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001616 }
1617 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001618
1619 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001620 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001621
Eric Laurente552edb2014-03-10 17:42:56 -07001622 // apply volume rules for current stream and device if necessary
1623 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001624 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001625 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001626 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001627
1628 // update the outputs if starting an output with a stream that can affect notification
1629 // routing
1630 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001631
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001632 // force reevaluating accessibility routing when ringtone or alarm starts
1633 if (strategy == STRATEGY_SONIFICATION) {
1634 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1635 }
Eric Laurentdc462862016-07-19 12:29:53 -07001636
1637 if (waitMs > muteWaitMs) {
1638 *delayMs = waitMs - muteWaitMs;
1639 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001640
1641 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1642 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1643 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1644 // change occurs after the MixerThread starts and causes a stream volume
1645 // glitch.
1646 //
1647 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001648 }
Eric Laurentdc462862016-07-19 12:29:53 -07001649
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001650 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1651 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1652 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1653 }
1654
Eric Laurent97ac8712018-07-27 18:59:02 -07001655 // Automatically enable the remote submix input when output is started on a re routing mix
1656 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001657 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001658 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1659 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1661 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001662 "remote-submix",
1663 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001664 }
1665
Eric Laurente552edb2014-03-10 17:42:56 -07001666 return NO_ERROR;
1667}
1668
Eric Laurent8fc147b2018-07-22 19:13:55 -07001669status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001670{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001671 ALOGV("%s portId %d", __FUNCTION__, portId);
1672
1673 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1674 if (outputDesc == 0) {
1675 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001676 return BAD_VALUE;
1677 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001678 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurent97ac8712018-07-27 18:59:02 -07001680 ALOGV("stopOutput() output %d, stream %d, session %d",
1681 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001682
Eric Laurent97ac8712018-07-27 18:59:02 -07001683 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001684
Eric Laurent733ce942017-12-07 12:18:25 -08001685 if (status == NO_ERROR ) {
1686 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001687 }
1688 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001689}
1690
Eric Laurent97ac8712018-07-27 18:59:02 -07001691status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1692 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001693{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001694 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001695 audio_stream_type_t stream = client->stream();
1696
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001697 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1698
Eric Laurent592dd7b2018-08-05 18:58:48 -07001699 if (outputDesc->streamActiveCount(stream) > 0) {
1700 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001701 // Automatically disable the remote submix input when output is stopped on a
1702 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001703 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001704 outputDesc->mPolicyMix != NULL &&
1705 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1706 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1707 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1708 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001709 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001710 }
1711 }
1712 bool forceDeviceUpdate = false;
1713 if (client->hasPreferredDevice(true)) {
1714 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1715 forceDeviceUpdate = true;
1716 }
1717
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001719 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001720
Eric Laurente552edb2014-03-10 17:42:56 -07001721 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001722 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001723 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001724 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001725 // delay the device switch by twice the latency because stopOutput() is executed when
1726 // the track stop() command is received and at that time the audio track buffer can
1727 // still contain data that needs to be drained. The latency only covers the audio HAL
1728 // and kernel buffers. Also the latency does not always include additional delay in the
1729 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001730 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001731
1732 // force restoring the device selection on other active outputs if it differs from the
1733 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001734 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001735 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001737 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001738 desc->isActive() &&
1739 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001740 (newDevices != desc->devices())) {
1741 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1742 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001743
François Gaffie11d30102018-11-02 16:09:09 +01001744 setOutputDevices(desc, newDevices2, force, delayMs);
1745
Eric Laurent57de36c2016-09-28 16:59:11 -07001746 // re-apply device specific volume if not done by setOutputDevice()
1747 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001748 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001749 }
Eric Laurente552edb2014-03-10 17:42:56 -07001750 }
1751 }
1752 // update the outputs if stopping one with a stream that can affect notification routing
1753 handleNotificationRoutingForStream(stream);
1754 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001755
1756 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1757 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1758 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1759 }
1760
Eric Laurent36829f92017-04-07 19:04:42 -07001761 if (stream == AUDIO_STREAM_MUSIC) {
1762 selectOutputForMusicEffects();
1763 }
Eric Laurente552edb2014-03-10 17:42:56 -07001764 return NO_ERROR;
1765 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001766 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001767 return INVALID_OPERATION;
1768 }
1769}
1770
Eric Laurent8fc147b2018-07-22 19:13:55 -07001771void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001772{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001773 ALOGV("%s portId %d", __FUNCTION__, portId);
1774
1775 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1776 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001777 // If an output descriptor is closed due to a device routing change,
1778 // then there are race conditions with releaseOutput from tracks
1779 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1780 // destroyed shortly thereafter.
1781 //
1782 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001783 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001784 return;
1785 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001786
1787 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Eric Laurent8fc147b2018-07-22 19:13:55 -07001789 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1790 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001791 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001792 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001793 return;
1794 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001795 if (--outputDesc->mDirectOpenCount == 0) {
1796 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001797 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001798 }
1799 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001800 // stopOutput() needs to be successfully called before releaseOutput()
1801 // otherwise there may be inaccurate stream reference counts.
1802 // This is checked in outputDesc->removeClient below.
1803 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001804}
1805
Eric Laurentcaf7f482014-11-25 17:50:47 -08001806status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1807 audio_io_handle_t *input,
1808 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001809 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001810 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001811 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001812 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001813 input_type_t *inputType,
1814 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001815{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001816 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001817 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001818 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001819
Eric Laurentad2e7b92017-09-14 20:06:42 -07001820 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001821 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001822 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001823 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001824 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001825 sp<AudioInputDescriptor> inputDesc;
1826 sp<RecordClientDescriptor> clientDesc;
1827 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001828 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001829
1830 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1831 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1832 return INVALID_OPERATION;
1833 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001834
Francois Gaffie716e1432019-01-14 16:58:59 +01001835 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1836 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001837 }
1838
Paul McLean466dc8e2015-04-17 13:15:36 -06001839 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001840 sp<DeviceDescriptor> explicitRoutingDevice =
1841 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001842
Eric Laurentad2e7b92017-09-14 20:06:42 -07001843 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1844 // possible
1845 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1846 *input != AUDIO_IO_HANDLE_NONE) {
1847 ssize_t index = mInputs.indexOfKey(*input);
1848 if (index < 0) {
1849 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1850 status = BAD_VALUE;
1851 goto error;
1852 }
1853 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001854 RecordClientVector clients = inputDesc->getClientsForSession(session);
1855 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001856 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1857 status = BAD_VALUE;
1858 goto error;
1859 }
1860 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1861 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001862 // corresponds to a new client and is only permitted from the same UID.
1863 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001864 if (clients.size() > 1) {
1865 for (const auto& client : clients) {
1866 // The client map is ordered by key values (portId) and portIds are allocated
1867 // incrementaly. So the first client in this list is the one opened by audio flinger
1868 // when the mmap stream is created and should be ignored as it does not correspond
1869 // to an actual client
1870 if (client == *clients.cbegin()) {
1871 continue;
1872 }
1873 if (uid != client->uid() && !client->isSilenced()) {
1874 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1875 uid, client->portId(), client->uid());
1876 status = INVALID_OPERATION;
1877 goto error;
1878 }
Eric Laurent331679c2018-04-16 17:03:16 -07001879 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001880 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001881 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001882 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001883
Eric Laurent8f42ea12018-08-08 09:08:25 -07001884 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001885 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001886 }
1887
1888 *input = AUDIO_IO_HANDLE_NONE;
1889 *inputType = API_INPUT_INVALID;
1890
Francois Gaffie716e1432019-01-14 16:58:59 +01001891 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001892
Francois Gaffie716e1432019-01-14 16:58:59 +01001893 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1894 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1895 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001896 if (status != NO_ERROR) {
1897 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001898 }
1899 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001900 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001901 String8(attr->tags + strlen("addr=")),
1902 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001903 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001904 if (explicitRoutingDevice != nullptr) {
1905 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001906 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001907 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001908 }
François Gaffie11d30102018-11-02 16:09:09 +01001909 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001910 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001911 status = BAD_VALUE;
1912 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001913 }
François Gaffie11d30102018-11-02 16:09:09 +01001914 if (policyMix != nullptr) {
1915 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1916 // there is an external policy, but this input is attached to a mix of recorders,
1917 // meaning it receives audio injected into the framework, so the recorder doesn't
1918 // know about it and is therefore considered "legacy"
1919 *inputType = API_INPUT_LEGACY;
1920 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001921 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1922 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001923 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001924 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001925 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001926 } else {
1927 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001928 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001929
Eric Laurent599c7582015-12-07 18:05:55 -08001930 }
1931
Francois Gaffie716e1432019-01-14 16:58:59 +01001932 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001933 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001934 policyMix);
1935 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001936 status = INVALID_OPERATION;
1937 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001938 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001939
Eric Laurent8f42ea12018-08-08 09:08:25 -07001940exit:
1941
François Gaffie11d30102018-11-02 16:09:09 +01001942 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1943 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001944
Francois Gaffie716e1432019-01-14 16:58:59 +01001945 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001946 mSoundTriggerSessions.indexOfKey(session) > 0;
1947 *portId = AudioPort::getNextUniqueId();
1948
François Gaffie11d30102018-11-02 16:09:09 +01001949 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001950 requestedDeviceId, attributes.source, flags,
1951 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001952 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001953 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001954
1955 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1956 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001957
Eric Laurent599c7582015-12-07 18:05:55 -08001958 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001959
1960error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001961 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001962}
1963
1964
François Gaffie11d30102018-11-02 16:09:09 +01001965audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001966 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001967 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001968 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001969 audio_input_flags_t flags,
1970 AudioMix *policyMix)
1971{
1972 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1973 audio_source_t halInputSource = inputSource;
1974 bool isSoundTrigger = false;
1975
1976 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1977 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1978 if (index >= 0) {
1979 input = mSoundTriggerSessions.valueFor(session);
1980 isSoundTrigger = true;
1981 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1982 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1983 } else {
1984 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001985 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001986 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001987 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001988 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001989 }
1990
Andy Hungf129b032015-04-07 13:45:50 -07001991 // find a compatible input profile (not necessarily identical in parameters)
1992 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001993 // sampling rate and flags may be updated by getInputProfile
1994 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1995 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001996 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001997 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001998 audio_input_flags_t profileFlags = flags;
1999 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002000 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002001 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002002 profileFlags);
2003 if (profile != 0) {
2004 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002005 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2006 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002007 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2008 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2009 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002010 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2011 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2012 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002013 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002014 }
Eric Laurente552edb2014-03-10 17:42:56 -07002015 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002016 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002017 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002018 if (samplingRate == 0) {
2019 samplingRate = profileSamplingRate;
2020 }
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurent322b4d22015-04-03 15:57:54 -07002022 if (profile->getModuleHandle() == 0) {
2023 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002024 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002025 }
2026
Eric Laurent3974e3b2017-12-07 17:58:43 -08002027 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002028 for (size_t i = 0; i < mInputs.size(); ) {
2029 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2030 if (desc->mProfile != profile) {
2031 continue;
2032 }
2033 // if sound trigger, reuse input if used by other sound trigger on same session
2034 // else
2035 // reuse input if active client app is not in IDLE state
2036 //
2037 RecordClientVector clients = desc->clientsList();
2038 bool doClose = false;
2039 for (const auto& client : clients) {
2040 if (isSoundTrigger != client->isSoundTrigger()) {
2041 continue;
2042 }
2043 if (client->isSoundTrigger()) {
2044 if (session == client->session()) {
2045 return desc->mIoHandle;
2046 }
2047 continue;
2048 }
2049 if (client->active() && client->appState() != APP_STATE_IDLE) {
2050 return desc->mIoHandle;
2051 }
2052 doClose = true;
2053 }
2054 if (doClose) {
2055 closeInput(desc->mIoHandle);
2056 } else {
2057 i++;
2058 }
2059 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002060 }
2061
Eric Laurentfe231122017-11-17 17:48:06 -08002062 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002063
Eric Laurentfe231122017-11-17 17:48:06 -08002064 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2065 lConfig.sample_rate = profileSamplingRate;
2066 lConfig.channel_mask = profileChannelMask;
2067 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002068
François Gaffie11d30102018-11-02 16:09:09 +01002069 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002070
2071 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002072 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002073 (profileSamplingRate != lConfig.sample_rate) ||
2074 !audio_formats_match(profileFormat, lConfig.format) ||
2075 (profileChannelMask != lConfig.channel_mask)) {
2076 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002077 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002078 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002079 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002080 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002081 }
Eric Laurent599c7582015-12-07 18:05:55 -08002082 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084
Eric Laurentc722f302014-12-10 11:21:49 -08002085 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002086
Eric Laurent599c7582015-12-07 18:05:55 -08002087 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002088 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002089
Eric Laurent599c7582015-12-07 18:05:55 -08002090 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002091}
2092
Eric Laurent4eb58f12018-12-07 16:41:02 -08002093status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 ALOGV("%s portId %d", __FUNCTION__, portId);
2096
2097 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2098 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002099 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100 return BAD_VALUE;
2101 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002103 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002104 if (client->active()) {
2105 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2106 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002107 }
2108
Eric Laurent8f42ea12018-08-08 09:08:25 -07002109 audio_session_t session = client->session();
2110
Eric Laurent4eb58f12018-12-07 16:41:02 -08002111 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112
Eric Laurent4eb58f12018-12-07 16:41:02 -08002113 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002114
Eric Laurent4eb58f12018-12-07 16:41:02 -08002115 status_t status = inputDesc->start();
2116 if (status != NO_ERROR) {
2117 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002118 }
Eric Laurente552edb2014-03-10 17:42:56 -07002119
Eric Laurent4eb58f12018-12-07 16:41:02 -08002120 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002121 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002123
Eric Laurent8f42ea12018-08-08 09:08:25 -07002124 // indicate active capture to sound trigger service if starting capture from a mic on
2125 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002126 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002127 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002128
Eric Laurent8f42ea12018-08-08 09:08:25 -07002129 if (inputDesc->activeCount() == 1) {
2130 // if input maps to a dynamic policy with an activity listener, notify of state change
2131 if ((inputDesc->mPolicyMix != NULL)
2132 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2133 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2134 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002135 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002136
François Gaffie11d30102018-11-02 16:09:09 +01002137 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2138 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002139 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2140 SoundTrigger::setCaptureState(true);
2141 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002142
Eric Laurent8f42ea12018-08-08 09:08:25 -07002143 // automatically enable the remote submix output when input is started if not
2144 // used by a policy mix of type MIX_TYPE_RECORDERS
2145 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002146 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 String8 address = String8("");
2148 if (inputDesc->mPolicyMix == NULL) {
2149 address = String8("0");
2150 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2151 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002152 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 if (address != "") {
2154 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2155 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002156 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002157 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002158 }
Eric Laurente552edb2014-03-10 17:42:56 -07002159 }
2160
Eric Laurent8f42ea12018-08-08 09:08:25 -07002161 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurente552edb2014-03-10 17:42:56 -07002163 return NO_ERROR;
2164}
2165
Eric Laurent8fc147b2018-07-22 19:13:55 -07002166status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002167{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168 ALOGV("%s portId %d", __FUNCTION__, portId);
2169
2170 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2171 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002173 return BAD_VALUE;
2174 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002175 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002176 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002177 if (!client->active()) {
2178 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002179 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002180 }
2181
Eric Laurent8f42ea12018-08-08 09:08:25 -07002182 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002183
Eric Laurent8f42ea12018-08-08 09:08:25 -07002184 inputDesc->stop();
2185 if (inputDesc->isActive()) {
2186 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2187 } else {
2188 // if input maps to a dynamic policy with an activity listener, notify of state change
2189 if ((inputDesc->mPolicyMix != NULL)
2190 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2191 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2192 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002193 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002194
2195 // automatically disable the remote submix output when input is stopped if not
2196 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002197 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002198 String8 address = String8("");
2199 if (inputDesc->mPolicyMix == NULL) {
2200 address = String8("0");
2201 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2202 address = inputDesc->mPolicyMix->mDeviceAddress;
2203 }
2204 if (address != "") {
2205 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2206 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002207 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 }
2209 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 resetInputDevice(input);
2211
2212 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2213 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002214 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2215 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2217 SoundTrigger::setCaptureState(false);
2218 }
2219 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002220 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002221 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002222}
2223
Eric Laurent8fc147b2018-07-22 19:13:55 -07002224void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002225{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226 ALOGV("%s portId %d", __FUNCTION__, portId);
2227
2228 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2229 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002231 return;
2232 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002233 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234 audio_io_handle_t input = inputDesc->mIoHandle;
2235
Eric Laurent8f42ea12018-08-08 09:08:25 -07002236 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002237
Andy Hung39efb7a2018-09-26 15:39:28 -07002238 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002239
Andy Hung39efb7a2018-09-26 15:39:28 -07002240 if (inputDesc->getClientCount() > 0) {
2241 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002242 return;
2243 }
2244
Eric Laurent05b90f82014-08-27 15:32:29 -07002245 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002246 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002247 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002248}
2249
Eric Laurent8f42ea12018-08-08 09:08:25 -07002250void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002251{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002252 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253
2254 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002255 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002256 }
2257}
2258
Eric Laurent8f42ea12018-08-08 09:08:25 -07002259void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2260{
2261 stopInput(portId);
2262 releaseInput(portId);
2263}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264
Eric Laurentd4692962014-05-05 18:13:44 -07002265void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002266 bool patchRemoved = false;
2267
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002268 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002269 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002270 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002271 if (patch_index >= 0) {
2272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002273 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002274 mAudioPatches.removeItemsAt(patch_index);
2275 patchRemoved = true;
2276 }
Eric Laurentfe231122017-11-17 17:48:06 -08002277 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002278 }
2279 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002280 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002281 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002282
2283 if (patchRemoved) {
2284 mpClientInterface->onAudioPatchListUpdate();
2285 }
Eric Laurentd4692962014-05-05 18:13:44 -07002286}
2287
Eric Laurente0720872014-03-11 09:30:41 -07002288void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002289 int indexMin,
2290 int indexMax)
2291{
2292 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002293 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002294
2295 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002296 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2297 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002298 continue;
2299 }
2300 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002301 }
Eric Laurente552edb2014-03-10 17:42:56 -07002302}
2303
Eric Laurente0720872014-03-11 09:30:41 -07002304status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002305 int index,
2306 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002307{
2308
Nadav Bar7c605f62017-12-25 00:01:52 +02002309 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2310 // app that has MODIFY_PHONE_STATE permission.
2311 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2312 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002313 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002314 return BAD_VALUE;
2315 }
2316 if (!audio_is_output_device(device)) {
2317 return BAD_VALUE;
2318 }
2319
2320 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002321 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002322
Eric Laurent1fd372e2016-04-06 14:23:53 -07002323 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002324 stream, device, index);
2325
Eric Laurent28d09f02016-03-08 10:43:05 -08002326 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002327 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2328 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002329 continue;
2330 }
2331 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2332 }
Eric Laurente552edb2014-03-10 17:42:56 -07002333
Eric Laurent1fd372e2016-04-06 14:23:53 -07002334 // update volume on all outputs and streams matching the following:
2335 // - The requested stream (or a stream matching for volume control) is active on the output
2336 // - The device (or devices) selected by the strategy corresponding to this stream includes
2337 // the requested device
2338 // - For non default requested device, currently selected device on the output is either the
2339 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002340 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2341 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002342 status_t status = NO_ERROR;
2343 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002344 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002345 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002346 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002347 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002348 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002349 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002350 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002351 continue;
2352 }
Eric Laurent794fde22016-03-11 09:50:45 -08002353 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002354 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2355 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002356 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2357 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002358 continue;
2359 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002360 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002361 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002362 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002363 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002364 } else {
2365 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002366 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002367 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002368 // rescale index before applying to curStream as ranges may be different for
2369 // stream and curStream
2370 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002371 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002372 //FIXME: workaround for truncated touch sounds
2373 // delayed volume change for system stream to be removed when the problem is
2374 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002375 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002376 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002377 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002378 if (volStatus != NO_ERROR) {
2379 status = volStatus;
2380 }
2381 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002382 }
Eric Laurente552edb2014-03-10 17:42:56 -07002383 }
2384 return status;
2385}
2386
Eric Laurente0720872014-03-11 09:30:41 -07002387status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002388 int *index,
2389 audio_devices_t device)
2390{
2391 if (index == NULL) {
2392 return BAD_VALUE;
2393 }
2394 if (!audio_is_output_device(device)) {
2395 return BAD_VALUE;
2396 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002397 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002398 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002399 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002400 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2401 }
François Gaffiedfd74092015-03-19 12:10:59 +01002402 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002403
François Gaffied1ab2bd2015-12-02 18:20:06 +01002404 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002405 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2406 return NO_ERROR;
2407}
2408
Eric Laurent36829f92017-04-07 19:04:42 -07002409audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002410{
2411 // select one output among several suitable for global effects.
2412 // The priority is as follows:
2413 // 1: An offloaded output. If the effect ends up not being offloadable,
2414 // AudioFlinger will invalidate the track and the offloaded output
2415 // will be closed causing the effect to be moved to a PCM output.
2416 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002417 // 3: The primary output
2418 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002419
Eric Laurent3b73df72014-03-11 09:06:29 -07002420 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002421 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2422 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002423
Eric Laurent36829f92017-04-07 19:04:42 -07002424 if (outputs.size() == 0) {
2425 return AUDIO_IO_HANDLE_NONE;
2426 }
Eric Laurente552edb2014-03-10 17:42:56 -07002427
Eric Laurent36829f92017-04-07 19:04:42 -07002428 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2429 bool activeOnly = true;
2430
2431 while (output == AUDIO_IO_HANDLE_NONE) {
2432 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2433 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2434 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2435
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002436 for (audio_io_handle_t output : outputs) {
2437 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002438 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2439 continue;
2440 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002441 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2442 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002443 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002444 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002445 }
2446 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002447 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002448 }
2449 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002450 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002451 }
2452 }
2453 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2454 output = outputOffloaded;
2455 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2456 output = outputDeepBuffer;
2457 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2458 output = outputPrimary;
2459 } else {
2460 output = outputs[0];
2461 }
2462 activeOnly = false;
2463 }
2464
2465 if (output != mMusicEffectOutput) {
2466 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2467 mMusicEffectOutput = output;
2468 }
2469
2470 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002471 return output;
2472}
2473
Eric Laurent36829f92017-04-07 19:04:42 -07002474audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2475{
2476 return selectOutputForMusicEffects();
2477}
2478
Eric Laurente0720872014-03-11 09:30:41 -07002479status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002480 audio_io_handle_t io,
2481 uint32_t strategy,
2482 int session,
2483 int id)
2484{
2485 ssize_t index = mOutputs.indexOfKey(io);
2486 if (index < 0) {
2487 index = mInputs.indexOfKey(io);
2488 if (index < 0) {
2489 ALOGW("registerEffect() unknown io %d", io);
2490 return INVALID_OPERATION;
2491 }
2492 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002493 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002494}
2495
Eric Laurentc241b0d2018-11-28 09:08:49 -08002496status_t AudioPolicyManager::unregisterEffect(int id)
2497{
2498 if (mEffects.getEffect(id) == nullptr) {
2499 return INVALID_OPERATION;
2500 }
2501
2502 if (mEffects.isEffectEnabled(id)) {
2503 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2504 setEffectEnabled(id, false);
2505 }
2506 return mEffects.unregisterEffect(id);
2507}
2508
2509status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2510{
2511 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2512 if (effect == nullptr) {
2513 return INVALID_OPERATION;
2514 }
2515
2516 status_t status = mEffects.setEffectEnabled(id, enabled);
2517 if (status == NO_ERROR) {
2518 mInputs.trackEffectEnabled(effect, enabled);
2519 }
2520 return status;
2521}
2522
Eric Laurentc75307b2015-03-17 15:29:32 -07002523bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2524{
Eric Laurent28d09f02016-03-08 10:43:05 -08002525 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002526 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2527 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002528 continue;
2529 }
2530 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2531 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002532 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002533}
2534
2535bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2536{
2537 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2538}
2539
Eric Laurente0720872014-03-11 09:30:41 -07002540bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002541{
2542 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002543 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002544 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002545 return true;
2546 }
2547 }
2548 return false;
2549}
2550
Eric Laurent275e8e92014-11-30 15:14:47 -08002551// Register a list of custom mixes with their attributes and format.
2552// When a mix is registered, corresponding input and output profiles are
2553// added to the remote submix hw module. The profile contains only the
2554// parameters (sampling rate, format...) specified by the mix.
2555// The corresponding input remote submix device is also connected.
2556//
2557// When a remote submix device is connected, the address is checked to select the
2558// appropriate profile and the corresponding input or output stream is opened.
2559//
2560// When capture starts, getInputForAttr() will:
2561// - 1 look for a mix matching the address passed in attribtutes tags if any
2562// - 2 if none found, getDeviceForInputSource() will:
2563// - 2.1 look for a mix matching the attributes source
2564// - 2.2 if none found, default to device selection by policy rules
2565// At this time, the corresponding output remote submix device is also connected
2566// and active playback use cases can be transferred to this mix if needed when reconnecting
2567// after AudioTracks are invalidated
2568//
2569// When playback starts, getOutputForAttr() will:
2570// - 1 look for a mix matching the address passed in attribtutes tags if any
2571// - 2 if none found, look for a mix matching the attributes usage
2572// - 3 if none found, default to device and output selection by policy rules.
2573
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002574status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002575{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2577 status_t res = NO_ERROR;
2578
2579 sp<HwModule> rSubmixModule;
2580 // examine each mix's route type
2581 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002582 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002584 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002586 break;
2587 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002588 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002590 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002591 rSubmixModule = mHwModules.getModuleFromName(
2592 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2593 if (rSubmixModule == 0) {
2594 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2595 i);
2596 res = INVALID_OPERATION;
2597 break;
2598 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002599 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002600
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 String8 address = mix.mDeviceAddress;
2602 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2603 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2604 } else {
2605 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2606 }
François Gaffie036e1e92015-03-19 10:16:24 +01002607
Eric Laurent97ac8712018-07-27 18:59:02 -07002608 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002609 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002610 res = INVALID_OPERATION;
2611 break;
2612 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002613 audio_config_t outputConfig = mix.mFormat;
2614 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2616 // stereo and let audio flinger do the channel conversion if needed.
2617 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2618 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2619 rSubmixModule->addOutputProfile(address, &outputConfig,
2620 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2621 rSubmixModule->addInputProfile(address, &inputConfig,
2622 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002623
Eric Laurent97ac8712018-07-27 18:59:02 -07002624 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002625 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002627 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 } else {
2629 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2630 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002631 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002633 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2634 String8 address = mix.mDeviceAddress;
2635 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002636 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2637 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002639 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002640 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2641 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2642 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2643 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2644 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2645 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002646 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2647 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002648 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002650 } else {
2651 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002652 }
2653 break;
2654 }
2655 }
2656
2657 if (res != NO_ERROR) {
2658 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002659 i, device, address.string());
2660 res = INVALID_OPERATION;
2661 break;
2662 } else if (!foundOutput) {
2663 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2664 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002665 res = INVALID_OPERATION;
2666 break;
2667 }
Eric Laurentc722f302014-12-10 11:21:49 -08002668 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002669 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002670 if (res != NO_ERROR) {
2671 unregisterPolicyMixes(mixes);
2672 }
2673 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002674}
2675
2676status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2677{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002678 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002679 status_t res = NO_ERROR;
2680 sp<HwModule> rSubmixModule;
2681 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002682 for (const auto& mix : mixes) {
2683 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002684
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002685 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002686 rSubmixModule = mHwModules.getModuleFromName(
2687 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2688 if (rSubmixModule == 0) {
2689 res = INVALID_OPERATION;
2690 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002691 }
2692 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002693
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002694 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002695
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002696 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2697 res = INVALID_OPERATION;
2698 continue;
2699 }
2700
2701 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2702 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2703 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2704 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002705 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002706 }
2707 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2708 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2709 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2710 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002711 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002712 }
2713 rSubmixModule->removeOutputProfile(address);
2714 rSubmixModule->removeInputProfile(address);
2715
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002716 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2717 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002718 res = INVALID_OPERATION;
2719 continue;
2720 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002721 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002722 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002723 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002724}
2725
Mikhail Naganov100f0122018-11-29 11:22:16 -08002726void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2727{
2728 size_t i = 0;
2729 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2730 for (const auto& fmt : mManualSurroundFormats) {
2731 if (i++ != 0) dst->append(", ");
2732 std::string sfmt;
2733 FormatConverter::toString(fmt, sfmt);
2734 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2735 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2736 }
2737}
2738
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002739status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2740 const Vector<AudioDeviceTypeAddr>& devices) {
2741 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2742 // uid/device affinity is only for output devices
2743 for (size_t i = 0; i < devices.size(); i++) {
2744 if (!audio_is_output_device(devices[i].mType)) {
2745 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2746 devices[i].mType);
2747 return BAD_VALUE;
2748 }
2749 }
2750 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2751 if (res == NO_ERROR) {
2752 // reevaluate outputs for all given devices
2753 for (size_t i = 0; i < devices.size(); i++) {
2754 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002755 devices[i].mType, devices[i].mAddress, String8(),
2756 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002757 SortedVector<audio_io_handle_t> outputs;
2758 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002759 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002760 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2761 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2762 return INVALID_OPERATION;
2763 }
2764 }
2765 }
2766 return res;
2767}
2768
2769status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2770 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2771 Vector<AudioDeviceTypeAddr> devices;
2772 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2773 if (res == NO_ERROR) {
2774 // reevaluate outputs for all found devices
2775 for (size_t i = 0; i < devices.size(); i++) {
2776 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002777 devices[i].mType, devices[i].mAddress, String8(),
2778 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002779 SortedVector<audio_io_handle_t> outputs;
2780 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002781 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002782 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2783 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2784 return INVALID_OPERATION;
2785 }
2786 }
2787 }
2788
2789 return res;
2790}
2791
Andy Hungc29d82b2018-10-05 12:23:17 -07002792void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002793{
Andy Hungc29d82b2018-10-05 12:23:17 -07002794 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2795 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002796 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002797 std::string stateLiteral;
2798 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002799 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002800 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2801 "communications", "media", "record", "dock", "system",
2802 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2803 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2804 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002805 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2806 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2807 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2808 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2809 dst->append(" (MANUAL: ");
2810 dumpManualSurroundFormats(dst);
2811 dst->append(")");
2812 }
2813 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002814 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002815 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2816 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2817 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2818 mAvailableOutputDevices.dump(dst, String8("Available output"));
2819 mAvailableInputDevices.dump(dst, String8("Available input"));
2820 mHwModulesAll.dump(dst);
2821 mOutputs.dump(dst);
2822 mInputs.dump(dst);
2823 mVolumeCurves->dump(dst);
2824 mEffects.dump(dst);
2825 mAudioPatches.dump(dst);
2826 mPolicyMixes.dump(dst);
2827 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002828}
2829
2830status_t AudioPolicyManager::dump(int fd)
2831{
2832 String8 result;
2833 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002834 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002835 return NO_ERROR;
2836}
2837
2838// This function checks for the parameters which can be offloaded.
2839// This can be enhanced depending on the capability of the DSP and policy
2840// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002841bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002842{
2843 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002844 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002845 offloadInfo.sample_rate, offloadInfo.channel_mask,
2846 offloadInfo.format,
2847 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2848 offloadInfo.has_video);
2849
Andy Hung2ddee192015-12-18 17:34:44 -08002850 if (mMasterMono) {
2851 return false; // no offloading if mono is set.
2852 }
2853
Eric Laurente552edb2014-03-10 17:42:56 -07002854 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002855 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2856 ALOGV("offload disabled by audio.offload.disable");
2857 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002858 }
2859
2860 // Check if stream type is music, then only allow offload as of now.
2861 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2862 {
2863 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2864 return false;
2865 }
2866
2867 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002868 const bool allowOffloadWithVideo =
2869 property_get_bool("audio.offload.video", false /* default_value */);
2870 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002871 ALOGV("isOffloadSupported: has_video == true, returning false");
2872 return false;
2873 }
2874
2875 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002876 const int min_duration_secs = property_get_int32(
2877 "audio.offload.min.duration.secs", -1 /* default_value */);
2878 if (min_duration_secs >= 0) {
2879 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2880 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2881 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002882 return false;
2883 }
2884 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2885 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2886 return false;
2887 }
2888
2889 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2890 // creating an offloaded track and tearing it down immediately after start when audioflinger
2891 // detects there is an active non offloadable effect.
2892 // FIXME: We should check the audio session here but we do not have it in this context.
2893 // This may prevent offloading in rare situations where effects are left active by apps
2894 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002895 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002896 return false;
2897 }
2898
2899 // See if there is a profile to support this.
2900 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002901 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002902 offloadInfo.sample_rate,
2903 offloadInfo.format,
2904 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002905 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2906 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002907 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2908 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002909}
2910
Michael Chana94fbb22018-04-24 14:31:19 +10002911bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2912 const audio_attributes_t& attributes) {
2913 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2914 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002915 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002916 config.sample_rate,
2917 config.format,
2918 config.channel_mask,
2919 output_flags,
2920 true /* directOnly */);
2921 ALOGV("%s() profile %sfound with name: %s, "
2922 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2923 __FUNCTION__, profile != 0 ? "" : "NOT ",
2924 (profile != 0 ? profile->getTagName().string() : "null"),
2925 config.sample_rate, config.format, config.channel_mask, output_flags);
2926 return (profile != 0);
2927}
2928
Eric Laurent6a94d692014-05-20 11:18:06 -07002929status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2930 audio_port_type_t type,
2931 unsigned int *num_ports,
2932 struct audio_port *ports,
2933 unsigned int *generation)
2934{
2935 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2936 generation == NULL) {
2937 return BAD_VALUE;
2938 }
2939 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2940 if (ports == NULL) {
2941 *num_ports = 0;
2942 }
2943
2944 size_t portsWritten = 0;
2945 size_t portsMax = *num_ports;
2946 *num_ports = 0;
2947 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002948 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2949 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002950 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002951 for (const auto& dev : mAvailableOutputDevices) {
2952 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002953 continue;
2954 }
2955 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002956 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002957 }
2958 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002959 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002960 }
2961 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002962 for (const auto& dev : mAvailableInputDevices) {
2963 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002964 continue;
2965 }
2966 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002967 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002968 }
2969 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 }
2972 }
2973 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2974 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2975 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2976 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2977 }
2978 *num_ports += mInputs.size();
2979 }
2980 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002981 size_t numOutputs = 0;
2982 for (size_t i = 0; i < mOutputs.size(); i++) {
2983 if (!mOutputs[i]->isDuplicated()) {
2984 numOutputs++;
2985 if (portsWritten < portsMax) {
2986 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2987 }
2988 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002989 }
Eric Laurent84c70242014-06-23 08:46:27 -07002990 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 }
2992 }
2993 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002994 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 return NO_ERROR;
2996}
2997
Eric Laurent99fcae42018-05-17 16:59:18 -07002998status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002999{
Eric Laurent99fcae42018-05-17 16:59:18 -07003000 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3001 return BAD_VALUE;
3002 }
3003 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3004 if (dev != 0) {
3005 dev->toAudioPort(port);
3006 return NO_ERROR;
3007 }
3008 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3009 if (dev != 0) {
3010 dev->toAudioPort(port);
3011 return NO_ERROR;
3012 }
3013 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3014 if (out != 0) {
3015 out->toAudioPort(port);
3016 return NO_ERROR;
3017 }
3018 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3019 if (in != 0) {
3020 in->toAudioPort(port);
3021 return NO_ERROR;
3022 }
3023 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003024}
3025
Eric Laurent6a94d692014-05-20 11:18:06 -07003026status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3027 audio_patch_handle_t *handle,
3028 uid_t uid)
3029{
3030 ALOGV("createAudioPatch()");
3031
3032 if (handle == NULL || patch == NULL) {
3033 return BAD_VALUE;
3034 }
3035 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3036
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003037 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003038 return BAD_VALUE;
3039 }
3040 // only one source per audio patch supported for now
3041 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 return INVALID_OPERATION;
3043 }
Eric Laurent874c42872014-08-08 15:13:39 -07003044
3045 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 return INVALID_OPERATION;
3047 }
Eric Laurent874c42872014-08-08 15:13:39 -07003048 for (size_t i = 0; i < patch->num_sinks; i++) {
3049 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3050 return INVALID_OPERATION;
3051 }
3052 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003053
3054 sp<AudioPatch> patchDesc;
3055 ssize_t index = mAudioPatches.indexOfKey(*handle);
3056
Eric Laurent6a94d692014-05-20 11:18:06 -07003057 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3058 patch->sources[0].role,
3059 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003060#if LOG_NDEBUG == 0
3061 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003062 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003063 patch->sinks[i].role,
3064 patch->sinks[i].type);
3065 }
3066#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003067
3068 if (index >= 0) {
3069 patchDesc = mAudioPatches.valueAt(index);
3070 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3071 mUidCached, patchDesc->mUid, uid);
3072 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3073 return INVALID_OPERATION;
3074 }
3075 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003076 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003077 }
3078
3079 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003080 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003081 if (outputDesc == NULL) {
3082 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3083 return BAD_VALUE;
3084 }
Eric Laurent84c70242014-06-23 08:46:27 -07003085 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3086 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003087 if (patchDesc != 0) {
3088 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3089 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3090 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3091 return BAD_VALUE;
3092 }
3093 }
Eric Laurent874c42872014-08-08 15:13:39 -07003094 DeviceVector devices;
3095 for (size_t i = 0; i < patch->num_sinks; i++) {
3096 // Only support mix to devices connection
3097 // TODO add support for mix to mix connection
3098 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3099 ALOGV("createAudioPatch() source mix but sink is not a device");
3100 return INVALID_OPERATION;
3101 }
3102 sp<DeviceDescriptor> devDesc =
3103 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3104 if (devDesc == 0) {
3105 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3106 return BAD_VALUE;
3107 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003108
François Gaffie11d30102018-11-02 16:09:09 +01003109 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003110 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003111 NULL, // updatedSamplingRate
3112 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003113 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003114 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003115 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003116 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003117 ALOGV("createAudioPatch() profile not supported for device %08x",
3118 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003119 return INVALID_OPERATION;
3120 }
3121 devices.add(devDesc);
3122 }
3123 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 return INVALID_OPERATION;
3125 }
Eric Laurent874c42872014-08-08 15:13:39 -07003126
Eric Laurent6a94d692014-05-20 11:18:06 -07003127 // TODO: reconfigure output format and channels here
3128 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003129 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003130 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003131 index = mAudioPatches.indexOfKey(*handle);
3132 if (index >= 0) {
3133 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3134 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3135 }
3136 patchDesc = mAudioPatches.valueAt(index);
3137 patchDesc->mUid = uid;
3138 ALOGV("createAudioPatch() success");
3139 } else {
3140 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3141 return INVALID_OPERATION;
3142 }
3143 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3144 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3145 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003146 // only one sink supported when connecting an input device to a mix
3147 if (patch->num_sinks > 1) {
3148 return INVALID_OPERATION;
3149 }
François Gaffie53615e22015-03-19 09:24:12 +01003150 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003151 if (inputDesc == NULL) {
3152 return BAD_VALUE;
3153 }
3154 if (patchDesc != 0) {
3155 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3156 return BAD_VALUE;
3157 }
3158 }
François Gaffie11d30102018-11-02 16:09:09 +01003159 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003160 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003161 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003162 return BAD_VALUE;
3163 }
3164
François Gaffie11d30102018-11-02 16:09:09 +01003165 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003166 patch->sinks[0].sample_rate,
3167 NULL, /*updatedSampleRate*/
3168 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003169 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003170 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003171 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003172 // FIXME for the parameter type,
3173 // and the NONE
3174 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003175 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 return INVALID_OPERATION;
3177 }
3178 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003179 ALOGV("%s() setting device %s on output %d", __func__,
3180 device->toString().c_str(), inputDesc->mIoHandle);
3181 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003182 index = mAudioPatches.indexOfKey(*handle);
3183 if (index >= 0) {
3184 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3185 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3186 }
3187 patchDesc = mAudioPatches.valueAt(index);
3188 patchDesc->mUid = uid;
3189 ALOGV("createAudioPatch() success");
3190 } else {
3191 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3192 return INVALID_OPERATION;
3193 }
3194 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3195 // device to device connection
3196 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003197 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 return BAD_VALUE;
3199 }
3200 }
François Gaffie11d30102018-11-02 16:09:09 +01003201 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003202 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003203 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003204 return BAD_VALUE;
3205 }
Eric Laurent874c42872014-08-08 15:13:39 -07003206
Eric Laurent6a94d692014-05-20 11:18:06 -07003207 //update source and sink with our own data as the data passed in the patch may
3208 // be incomplete.
3209 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003210 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003211
Eric Laurent874c42872014-08-08 15:13:39 -07003212 for (size_t i = 0; i < patch->num_sinks; i++) {
3213 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3214 ALOGV("createAudioPatch() source device but one sink is not a device");
3215 return INVALID_OPERATION;
3216 }
3217
François Gaffie11d30102018-11-02 16:09:09 +01003218 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003219 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003220 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003221 return BAD_VALUE;
3222 }
François Gaffie11d30102018-11-02 16:09:09 +01003223 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003224
Eric Laurent3bcf8592015-04-03 12:13:24 -07003225 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003226 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003227 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003228 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003229 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3230 (srcDevice->getModuleVersionMajor() < 3) ||
3231 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003232 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003233 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003234 return INVALID_OPERATION;
3235 }
Eric Laurent874c42872014-08-08 15:13:39 -07003236 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003237 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003238 // if the sink device is reachable via an opened output stream, request to go via
3239 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003240 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003241 if (output != AUDIO_IO_HANDLE_NONE) {
3242 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3243 if (outputDesc->isDuplicated()) {
3244 return INVALID_OPERATION;
3245 }
3246 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003247 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003248 newPatch.num_sources = 2;
3249 }
Eric Laurent83b88082014-06-20 18:31:16 -07003250 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003251 }
3252 // TODO: check from routing capabilities in config file and other conflicting patches
3253
Mikhail Naganovdc769682018-05-04 15:34:08 -07003254 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3255 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003256 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3257 status);
3258 return INVALID_OPERATION;
3259 }
3260 } else {
3261 return BAD_VALUE;
3262 }
3263 } else {
3264 return BAD_VALUE;
3265 }
3266 return NO_ERROR;
3267}
3268
3269status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3270 uid_t uid)
3271{
3272 ALOGV("releaseAudioPatch() patch %d", handle);
3273
3274 ssize_t index = mAudioPatches.indexOfKey(handle);
3275
3276 if (index < 0) {
3277 return BAD_VALUE;
3278 }
3279 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3280 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3281 mUidCached, patchDesc->mUid, uid);
3282 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3283 return INVALID_OPERATION;
3284 }
3285
3286 struct audio_patch *patch = &patchDesc->mPatch;
3287 patchDesc->mUid = mUidCached;
3288 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003289 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003290 if (outputDesc == NULL) {
3291 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3292 return BAD_VALUE;
3293 }
3294
François Gaffie11d30102018-11-02 16:09:09 +01003295 setOutputDevices(outputDesc,
3296 getNewOutputDevices(outputDesc, true /*fromCache*/),
3297 true,
3298 0,
3299 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003300 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3301 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003302 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 if (inputDesc == NULL) {
3304 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3305 return BAD_VALUE;
3306 }
3307 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003308 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003309 true,
3310 NULL);
3311 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003312 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3313 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3314 status, patchDesc->mAfPatchHandle);
3315 removeAudioPatch(patchDesc->mHandle);
3316 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003317 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003318 } else {
3319 return BAD_VALUE;
3320 }
3321 } else {
3322 return BAD_VALUE;
3323 }
3324 return NO_ERROR;
3325}
3326
3327status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3328 struct audio_patch *patches,
3329 unsigned int *generation)
3330{
François Gaffie53615e22015-03-19 09:24:12 +01003331 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003332 return BAD_VALUE;
3333 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003334 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003335 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003336}
3337
Eric Laurente1715a42014-05-20 11:30:42 -07003338status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003339{
Eric Laurente1715a42014-05-20 11:30:42 -07003340 ALOGV("setAudioPortConfig()");
3341
3342 if (config == NULL) {
3343 return BAD_VALUE;
3344 }
3345 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3346 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003347 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3348 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003349 }
3350
Eric Laurenta121f902014-06-03 13:32:54 -07003351 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003352 if (config->type == AUDIO_PORT_TYPE_MIX) {
3353 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003354 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003355 if (outputDesc == NULL) {
3356 return BAD_VALUE;
3357 }
Eric Laurent84c70242014-06-23 08:46:27 -07003358 ALOG_ASSERT(!outputDesc->isDuplicated(),
3359 "setAudioPortConfig() called on duplicated output %d",
3360 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003361 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003362 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003363 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003364 if (inputDesc == NULL) {
3365 return BAD_VALUE;
3366 }
Eric Laurenta121f902014-06-03 13:32:54 -07003367 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003368 } else {
3369 return BAD_VALUE;
3370 }
3371 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3372 sp<DeviceDescriptor> deviceDesc;
3373 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3374 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3375 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3376 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3377 } else {
3378 return BAD_VALUE;
3379 }
3380 if (deviceDesc == NULL) {
3381 return BAD_VALUE;
3382 }
Eric Laurenta121f902014-06-03 13:32:54 -07003383 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003384 } else {
3385 return BAD_VALUE;
3386 }
3387
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003388 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003389 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3390 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003391 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003392 audioPortConfig->toAudioPortConfig(&newConfig, config);
3393 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003394 }
Eric Laurenta121f902014-06-03 13:32:54 -07003395 if (status != NO_ERROR) {
3396 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003397 }
Eric Laurente1715a42014-05-20 11:30:42 -07003398
3399 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003400}
3401
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003402void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3403{
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003405 clearAudioPatches(uid);
3406 clearSessionRoutes(uid);
3407}
3408
Eric Laurent6a94d692014-05-20 11:18:06 -07003409void AudioPolicyManager::clearAudioPatches(uid_t uid)
3410{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003411 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003412 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3413 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003414 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003415 }
3416 }
3417}
3418
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003419void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3420 audio_io_handle_t ouptutToSkip)
3421{
François Gaffie11d30102018-11-02 16:09:09 +01003422 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3423 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003424 for (size_t j = 0; j < mOutputs.size(); j++) {
3425 if (mOutputs.keyAt(j) == ouptutToSkip) {
3426 continue;
3427 }
3428 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3429 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3430 continue;
3431 }
3432 // If the default device for this strategy is on another output mix,
3433 // invalidate all tracks in this strategy to force re connection.
3434 // Otherwise select new device on the output mix.
3435 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003436 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003437 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3438 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3439 }
3440 }
3441 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003442 setOutputDevices(
3443 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003444 }
3445 }
3446}
3447
3448void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3449{
3450 // remove output routes associated with this uid
3451 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003452 for (size_t i = 0; i < mOutputs.size(); i++) {
3453 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003454 for (const auto& client : outputDesc->getClientIterable()) {
3455 if (client->hasPreferredDevice() && client->uid() == uid) {
3456 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3457 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003458 }
3459 }
3460 }
3461 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003462 for (const auto& strategy : affectedStrategies) {
3463 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003464 }
3465
3466 // remove input routes associated with this uid
3467 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003468 for (size_t i = 0; i < mInputs.size(); i++) {
3469 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003470 for (const auto& client : inputDesc->getClientIterable()) {
3471 if (client->hasPreferredDevice() && client->uid() == uid) {
3472 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3473 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003474 }
3475 }
3476 }
3477 // reroute inputs if necessary
3478 SortedVector<audio_io_handle_t> inputsToClose;
3479 for (size_t i = 0; i < mInputs.size(); i++) {
3480 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003481 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003482 inputsToClose.add(inputDesc->mIoHandle);
3483 }
3484 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003485 for (const auto& input : inputsToClose) {
3486 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003487 }
3488}
3489
Eric Laurentd60560a2015-04-10 11:31:20 -07003490void AudioPolicyManager::clearAudioSources(uid_t uid)
3491{
3492 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003493 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3494 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003495 stopAudioSource(mAudioSources.keyAt(i));
3496 }
3497 }
3498}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003499
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003500status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3501 audio_io_handle_t *ioHandle,
3502 audio_devices_t *device)
3503{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003504 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3505 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003506 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3507 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003508
François Gaffiedf372692015-03-19 10:43:27 +01003509 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003510}
3511
Eric Laurentd60560a2015-04-10 11:31:20 -07003512status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 const audio_attributes_t *attributes,
3514 audio_port_handle_t *portId,
3515 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003516{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003517 ALOGV("%s", __FUNCTION__);
3518 *portId = AUDIO_PORT_HANDLE_NONE;
3519
3520 if (source == NULL || attributes == NULL || portId == NULL) {
3521 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3522 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003523 return BAD_VALUE;
3524 }
3525
Eric Laurentd60560a2015-04-10 11:31:20 -07003526 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3527 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003528 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3529 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003530 return INVALID_OPERATION;
3531 }
3532
François Gaffie11d30102018-11-02 16:09:09 +01003533 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003534 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003535 String8(source->ext.device.address),
3536 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003537 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003538 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003539 return BAD_VALUE;
3540 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003541
3542 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003543
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003544 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003545 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003546
3547 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003548 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003549 streamTypefromAttributesInt(attributes),
3550 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003551
3552 status_t status = connectAudioSource(sourceDesc);
3553 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003554 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003555 }
3556 return status;
3557}
3558
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003559status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003560{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003561 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003562
3563 // make sure we only have one patch per source.
3564 disconnectAudioSource(sourceDesc);
3565
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003566 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003567 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003568 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003569 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003570
François Gaffie11d30102018-11-02 16:09:09 +01003571 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3572 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3573 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3574 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3575 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003576
3577 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003578
François Gaffie11d30102018-11-02 16:09:09 +01003579 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3580 srcDevice->getModuleVersionMajor() >= 3 &&
3581 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3582 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003583 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003584 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003585 // create patch between src device and output device
3586 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003587 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003588 audio_attributes_t resultAttr;
3589 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3590 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3591 config.sample_rate = sourceDesc->config().sample_rate;
3592 config.channel_mask = sourceDesc->config().channel_mask;
3593 config.format = sourceDesc->config().format;
3594 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3595 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3596 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3597 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003598 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003599 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003600 return INVALID_OPERATION;
3601 }
3602 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3603 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003604 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003605 return INVALID_OPERATION;
3606 }
Eric Laurent733ce942017-12-07 12:18:25 -08003607 status_t status = outputDesc->start();
3608 if (status != NO_ERROR) {
3609 return status;
3610 }
3611
Eric Laurentd60560a2015-04-10 11:31:20 -07003612 // create a special patch with no sink and two sources:
3613 // - the second source indicates to PatchPanel through which output mix this patch should
3614 // be connected as well as the stream type for volume control
3615 // - the sink is defined by whatever output device is currently selected for the output
3616 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003617 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003618 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003619 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003620 &afPatchHandle,
3621 0);
3622 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3623 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003624 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003625 if (status != NO_ERROR) {
3626 ALOGW("%s patch panel could not connect device patch, error %d",
3627 __FUNCTION__, status);
3628 return INVALID_OPERATION;
3629 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003630
3631 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3632 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3633 return INVALID_OPERATION;
3634 }
3635 outputDesc->addClient(sourceDesc);
3636
Eric Laurentd60560a2015-04-10 11:31:20 -07003637 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003638 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003639
3640 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003641 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003642 return status;
3643 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003644 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003645 if (delayMs != 0) {
3646 usleep(delayMs * 1000);
3647 }
3648 }
3649
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003650 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3651 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003652
3653 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003654}
3655
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003656status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003657{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003658 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3659 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003660 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003661 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003662 return BAD_VALUE;
3663 }
3664 status_t status = disconnectAudioSource(sourceDesc);
3665
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003666 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003667 return status;
3668}
3669
Andy Hung2ddee192015-12-18 17:34:44 -08003670status_t AudioPolicyManager::setMasterMono(bool mono)
3671{
3672 if (mMasterMono == mono) {
3673 return NO_ERROR;
3674 }
3675 mMasterMono = mono;
3676 // if enabling mono we close all offloaded devices, which will invalidate the
3677 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3678 // for recreating the new AudioTrack as non-offloaded PCM.
3679 //
3680 // If disabling mono, we leave all tracks as is: we don't know which clients
3681 // and tracks are able to be recreated as offloaded. The next "song" should
3682 // play back offloaded.
3683 if (mMasterMono) {
3684 Vector<audio_io_handle_t> offloaded;
3685 for (size_t i = 0; i < mOutputs.size(); ++i) {
3686 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3687 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3688 offloaded.push(desc->mIoHandle);
3689 }
3690 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003691 for (const auto& handle : offloaded) {
3692 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003693 }
3694 }
3695 // update master mono for all remaining outputs
3696 for (size_t i = 0; i < mOutputs.size(); ++i) {
3697 updateMono(mOutputs.keyAt(i));
3698 }
3699 return NO_ERROR;
3700}
3701
3702status_t AudioPolicyManager::getMasterMono(bool *mono)
3703{
3704 *mono = mMasterMono;
3705 return NO_ERROR;
3706}
3707
Eric Laurentac9cef52017-06-09 15:46:26 -07003708float AudioPolicyManager::getStreamVolumeDB(
3709 audio_stream_type_t stream, int index, audio_devices_t device)
3710{
3711 return computeVolume(stream, index, device);
3712}
3713
jiabin81772902018-04-02 17:52:27 -07003714status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3715 audio_format_t *surroundFormats,
3716 bool *surroundFormatsEnabled,
3717 bool reported)
3718{
3719 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3720 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3721 return BAD_VALUE;
3722 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003723 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3724 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003725
3726 size_t formatsWritten = 0;
3727 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003728 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003729 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003730 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003731 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003732 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3733 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3734 FormatVector supportedFormats =
3735 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3736 for (size_t j = 0; j < supportedFormats.size(); j++) {
3737 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3738 formats.insert(supportedFormats[j]);
3739 } else {
3740 for (const auto& pair : mConfig.getSurroundFormats()) {
3741 if (pair.second.count(supportedFormats[j]) != 0) {
3742 formats.insert(pair.first);
3743 break;
3744 }
3745 }
3746 }
3747 }
jiabin81772902018-04-02 17:52:27 -07003748 }
3749 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003750 for (const auto& pair : mConfig.getSurroundFormats()) {
3751 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003752 }
3753 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003754 *numSurroundFormats = formats.size();
3755 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3756 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003757 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003758 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003759 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003760 bool formatEnabled = true;
3761 switch (forceUse) {
3762 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3763 formatEnabled = mManualSurroundFormats.count(format) != 0;
3764 break;
3765 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3766 formatEnabled = false;
3767 break;
3768 default: // AUTO or ALWAYS => true
3769 break;
jiabin81772902018-04-02 17:52:27 -07003770 }
3771 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3772 }
jiabin81772902018-04-02 17:52:27 -07003773 }
3774 return NO_ERROR;
3775}
3776
3777status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3778{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003779 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003780 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3781 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003782 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003783 return BAD_VALUE;
3784 }
3785
Mikhail Naganov100f0122018-11-29 11:22:16 -08003786 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3787 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003788 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003789 return INVALID_OPERATION;
3790 }
3791
Mikhail Naganov100f0122018-11-29 11:22:16 -08003792 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003793 return NO_ERROR;
3794 }
3795
Mikhail Naganov100f0122018-11-29 11:22:16 -08003796 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003797 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003798 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003799 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003800 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003801 }
3802 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003803 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003804 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003805 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003806 }
3807 }
3808
3809 sp<SwAudioOutputDescriptor> outputDesc;
3810 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003811 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003812 AUDIO_DEVICE_OUT_HDMI);
3813 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3814 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003815 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003816 String8 name = hdmiOutputDevices[i]->getName();
3817 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3818 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3819 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003820 name.c_str(),
3821 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003822 if (status != NO_ERROR) {
3823 continue;
3824 }
3825 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3826 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3827 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003828 name.c_str(),
3829 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003830 profileUpdated |= (status == NO_ERROR);
3831 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003832 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003833 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003834 AUDIO_DEVICE_IN_HDMI);
3835 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3836 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003837 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003838 String8 name = hdmiInputDevices[i]->getName();
3839 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3840 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3841 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003842 name.c_str(),
3843 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003844 if (status != NO_ERROR) {
3845 continue;
3846 }
3847 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3848 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3849 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003850 name.c_str(),
3851 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003852 profileUpdated |= (status == NO_ERROR);
3853 }
3854
jiabin81772902018-04-02 17:52:27 -07003855 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003856 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003857 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003858 }
3859
3860 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3861}
3862
Eric Laurentf32108e2018-10-04 17:22:04 -07003863void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003864{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003865 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003866
Eric Laurenta9f86652018-11-28 17:23:11 -08003867 for (size_t i = 0; i < mInputs.size(); i++) {
3868 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3869 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003870 for (const auto& client : clients) {
3871 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003872 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003873 }
3874 }
3875 }
3876}
3877
jiabin6012f912018-11-02 17:06:30 -07003878bool AudioPolicyManager::isHapticPlaybackSupported()
3879{
3880 for (const auto& hwModule : mHwModules) {
3881 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3882 for (const auto &outProfile : outputProfiles) {
3883 struct audio_port audioPort;
3884 outProfile->toAudioPort(&audioPort);
3885 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3886 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3887 return true;
3888 }
3889 }
3890 }
3891 }
3892 return false;
3893}
3894
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003895status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003896{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003897 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003898
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003899 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003900 if (patchDesc == 0) {
3901 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003902 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003903 return BAD_VALUE;
3904 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003905 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003906
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003907 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003908 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003909 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003910 if (status == NO_ERROR) {
3911 swOutputDesc->stop();
3912 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003913 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3914 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003915 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003916 if (hwOutputDesc != 0) {
3917 // release patch between src device and output device
3918 // close Hwoutput and remove from mHwOutputs
3919 } else {
3920 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3921 }
3922 }
3923 return NO_ERROR;
3924}
3925
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003926sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003927 audio_io_handle_t output, routing_strategy strategy)
3928{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003929 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003930 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003931 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3932 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003933 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003934 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003935 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3936 source = sourceDesc;
3937 break;
3938 }
3939 }
3940 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003941}
3942
Eric Laurente552edb2014-03-10 17:42:56 -07003943// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003944// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003945// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003946uint32_t AudioPolicyManager::nextAudioPortGeneration()
3947{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003948 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003949}
3950
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003951// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3952static const char *kConfigLocationList[] =
3953 {"/odm/etc", "/vendor/etc", "/system/etc"};
3954static const int kConfigLocationListSize =
3955 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3956
3957static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3958 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003959 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003960 status_t ret;
3961
Petri Gyntherf497f292018-04-17 18:46:10 -07003962 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3963 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3964 // A2DP offload supported but disabled: try to use special XML file
3965 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3966 }
3967 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3968
3969 for (const char* fileName : fileNames) {
3970 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003971 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3972 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003973 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003974 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003975 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003976 return ret;
3977 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003978 }
3979 }
3980 return ret;
3981}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003982
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003983AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3984 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003985 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003986 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003987 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003988 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003989 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003990 mVolumeCurves(new VolumeCurvesCollection()),
3991 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003992 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003993 mAudioPortGeneration(1),
3994 mBeaconMuteRefCount(0),
3995 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003996 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003997 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003998 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003999 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004000{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004001}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004002
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004003AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4004 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4005{
4006 loadConfig();
4007 initialize();
4008}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004009
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004010// This check is to catch any legacy platform updating to Q without having
4011// switched to XML since its deprecation on O.
4012// TODO: after Q release, remove this check and flag as XML is now the only
4013// option and all legacy platform should have transitioned to XML.
4014#ifndef USE_XML_AUDIO_POLICY_CONF
4015#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004016#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004017
4018void AudioPolicyManager::loadConfig() {
4019 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004020 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004021 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004022 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004023}
4024
4025status_t AudioPolicyManager::initialize() {
4026 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004027
4028 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004029 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4030 if (!engineInstance) {
4031 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004032 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004033 }
4034 // Retrieve the Policy Manager Interface
4035 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4036 if (mEngine == NULL) {
4037 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004038 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004039 }
4040 mEngine->setObserver(this);
4041 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004042 if (status != NO_ERROR) {
4043 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4044 return status;
4045 }
François Gaffie2110e042015-03-24 08:41:51 +01004046
Eric Laurent3a4311c2014-03-17 12:00:47 -07004047 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004048 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004049 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004050 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004051 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4052 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004053 continue;
4054 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004055 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004056 // open all output streams needed to access attached devices
4057 // except for direct output streams that are only opened when they are actually
4058 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004060 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004061 if (!outProfile->canOpenNewIo()) {
4062 ALOGE("Invalid Output profile max open count %u for profile %s",
4063 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4064 continue;
4065 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004066 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004067 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 continue;
4069 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004070 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004071 mTtsOutputAvailable = true;
4072 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004073
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004074 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004075 continue;
4076 }
François Gaffie11d30102018-11-02 16:09:09 +01004077 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4078 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4079 sp<DeviceDescriptor> supportedDevice = 0;
4080 if (supportedDevices.contains(mDefaultOutputDevice)) {
4081 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004082 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004083 // choose first device present in profile's SupportedDevices also part of
4084 // mAvailableOutputDevices.
4085 if (availProfileDevices.isEmpty()) {
4086 continue;
4087 }
4088 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004089 }
François Gaffie11d30102018-11-02 16:09:09 +01004090 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004091 continue;
4092 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004093 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4094 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004095 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004096 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4097 AUDIO_STREAM_DEFAULT,
4098 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004099 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004100 ALOGW("Cannot open output stream for devices %s on hw module %s",
4101 supportedDevice->toString().c_str(), hwModule->getName());
4102 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004103 }
François Gaffie11d30102018-11-02 16:09:09 +01004104 for (const auto &device : availProfileDevices) {
4105 // give a valid ID to an attached device once confirmed it is reachable
4106 if (!device->isAttached()) {
4107 device->attach(hwModule);
4108 }
4109 }
4110 if (mPrimaryOutput == 0 &&
4111 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4112 mPrimaryOutput = outputDesc;
4113 }
4114 addOutput(output, outputDesc);
4115 setOutputDevices(outputDesc,
4116 DeviceVector(supportedDevice),
4117 true,
4118 0,
4119 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004121 // open input streams needed to access attached devices to validate
4122 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004123 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004124 if (!inProfile->canOpenNewIo()) {
4125 ALOGE("Invalid Input profile max open count %u for profile %s",
4126 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4127 continue;
4128 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004129 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004130 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004131 continue;
4132 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004133 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004134 // available input devices
4135 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4136 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4137 if (availProfileDevices.isEmpty()) {
4138 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004139 continue;
4140 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004141 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004142 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004143
Eric Laurentd78f1532014-09-16 16:38:20 -07004144 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004145 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004146 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004147 AUDIO_SOURCE_MIC,
4148 AUDIO_INPUT_FLAG_NONE,
4149 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004150 if (status != NO_ERROR) {
4151 ALOGW("Cannot open input stream for device %s on hw module %s",
4152 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004153 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004154 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004155 }
François Gaffie11d30102018-11-02 16:09:09 +01004156 for (const auto &device : availProfileDevices) {
4157 // give a valid ID to an attached device once confirmed it is reachable
4158 if (!device->isAttached()) {
4159 device->attach(hwModule);
4160 device->importAudioPort(inProfile, true);
4161 }
4162 }
4163 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004164 }
4165 }
4166 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004167 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004168 for (size_t i = 0; i < devices.size();) {
4169 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004170 if (!device->isAttached()) {
4171 ALOGW("device %s is unreachable", device->toString().c_str());
4172 devices.remove(device);
4173 continue;
4174 }
4175 // Device is now validated and can be appended to the available devices of the engine
4176 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004177 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004178 }
François Gaffie11d30102018-11-02 16:09:09 +01004179 };
4180 checkAndSetAvailable(mAvailableOutputDevices);
4181 checkAndSetAvailable(mAvailableInputDevices);
4182
Eric Laurent3a4311c2014-03-17 12:00:47 -07004183 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004184 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4185 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4186 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004187 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004188 }
jiabin9ff780e2018-03-19 18:19:52 -07004189 // If microphones address is empty, set it according to device type
4190 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004191 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004192 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004193 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004194 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004195 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004196 }
4197 }
4198 }
Eric Laurente552edb2014-03-10 17:42:56 -07004199
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004200 if (mPrimaryOutput == 0) {
4201 ALOGE("Failed to open primary output");
4202 status = NO_INIT;
4203 }
Eric Laurente552edb2014-03-10 17:42:56 -07004204
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004205 // Silence ALOGV statements
4206 property_set("log.tag." LOG_TAG, "D");
4207
Eric Laurente552edb2014-03-10 17:42:56 -07004208 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004209 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004210}
4211
Eric Laurente0720872014-03-11 09:30:41 -07004212AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004213{
Eric Laurente552edb2014-03-10 17:42:56 -07004214 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004215 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004216 }
4217 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004218 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004219 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004220 mAvailableOutputDevices.clear();
4221 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004222 mOutputs.clear();
4223 mInputs.clear();
4224 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004225 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004226 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004227}
4228
Eric Laurente0720872014-03-11 09:30:41 -07004229status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004230{
Eric Laurent87ffa392015-05-22 10:32:38 -07004231 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004232}
4233
Eric Laurente552edb2014-03-10 17:42:56 -07004234// ---
4235
Eric Laurent98e38192018-02-15 18:31:53 -08004236void AudioPolicyManager::addOutput(audio_io_handle_t output,
4237 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004238{
Eric Laurent1c333e22014-05-20 10:48:17 -07004239 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004240 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004241 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004242 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004243 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004244}
4245
François Gaffie53615e22015-03-19 09:24:12 +01004246void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4247{
4248 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004249 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004250}
4251
Eric Laurent98e38192018-02-15 18:31:53 -08004252void AudioPolicyManager::addInput(audio_io_handle_t input,
4253 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004254{
Eric Laurent1c333e22014-05-20 10:48:17 -07004255 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004256 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004257}
Eric Laurente552edb2014-03-10 17:42:56 -07004258
François Gaffie11d30102018-11-02 16:09:09 +01004259status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004260 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004261 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004262{
François Gaffie11d30102018-11-02 16:09:09 +01004263 audio_devices_t deviceType = device->type();
4264 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004265 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004266
François Gaffie11d30102018-11-02 16:09:09 +01004267 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004268 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004269 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004270 }
Eric Laurente552edb2014-03-10 17:42:56 -07004271
Eric Laurent3b73df72014-03-11 09:06:29 -07004272 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004273 // first list already open outputs that can be routed to this device
4274 for (size_t i = 0; i < mOutputs.size(); i++) {
4275 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004276 if (!desc->isDuplicated() && desc->supportsDevice(device)
4277 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004278 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4279 mOutputs.keyAt(i), device->toString().c_str());
4280 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004281 }
4282 }
4283 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004284 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004285 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004286 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4287 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004288 if (profile->supportsDevice(device)) {
4289 profiles.add(profile);
4290 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4291 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
4293 }
4294 }
4295
Eric Laurent7b279bb2015-12-14 10:18:23 -08004296 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004297
Eric Laurente552edb2014-03-10 17:42:56 -07004298 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004299 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004300 return BAD_VALUE;
4301 }
4302
4303 // open outputs for matching profiles if needed. Direct outputs are also opened to
4304 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4305 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004306 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004307
4308 // nothing to do if one output is already opened for this profile
4309 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004310 for (j = 0; j < outputs.size(); j++) {
4311 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004312 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004313 // matching profile: save the sample rates, format and channel masks supported
4314 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004315 if (audio_device_is_digital(deviceType)) {
4316 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004317 }
Eric Laurente552edb2014-03-10 17:42:56 -07004318 break;
4319 }
4320 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004321 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004322 continue;
4323 }
4324
Eric Laurent3974e3b2017-12-07 17:58:43 -08004325 if (!profile->canOpenNewIo()) {
4326 ALOGW("Max Output number %u already opened for this profile %s",
4327 profile->maxOpenCount, profile->getTagName().c_str());
4328 continue;
4329 }
4330
Eric Laurent83efe1c2017-07-09 16:51:08 -07004331 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004332 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004333 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004334 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004335 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004336 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004337
Eric Laurentfe231122017-11-17 17:48:06 -08004338 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004339 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004340 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004341 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004342 mpClientInterface->setParameters(output, String8(param));
4343 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
François Gaffie11d30102018-11-02 16:09:09 +01004345 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004346 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004348 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004349 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004350 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004351 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004352 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004353 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4354 profile->pickAudioProfile(
4355 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004356 config.offload_info.sample_rate = config.sample_rate;
4357 config.offload_info.channel_mask = config.channel_mask;
4358 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004359
François Gaffie11d30102018-11-02 16:09:09 +01004360 status_t status = desc->open(&config, DeviceVector(device),
4361 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004362 AUDIO_OUTPUT_FLAG_NONE, &output);
4363 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004364 output = AUDIO_IO_HANDLE_NONE;
4365 }
Eric Laurentd4692962014-05-05 18:13:44 -07004366 }
4367
Eric Laurentcf2c0212014-07-25 16:20:43 -07004368 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004369 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004370 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004371 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004372 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4373 policyMix->setOutput(desc);
4374 desc->mPolicyMix = policyMix->getMix();
4375 } else {
4376 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004377 address.string());
4378 }
François Gaffie036e1e92015-03-19 10:16:24 +01004379
Eric Laurent87ffa392015-05-22 10:32:38 -07004380 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4381 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004382 // no duplicated output for direct outputs and
4383 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004384 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004385
Eric Laurentd4692962014-05-05 18:13:44 -07004386 //TODO: configure audio effect output stage here
4387
4388 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004389 sp<SwAudioOutputDescriptor> dupOutputDesc =
4390 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4391 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4392 &duplicatedOutput);
4393 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004394 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004395 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004396 } else {
4397 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004398 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004399 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004400 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004402 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004403 }
Eric Laurente552edb2014-03-10 17:42:56 -07004404 }
4405 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004406 } else {
4407 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004408 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004409 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004410 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004411 profiles.removeAt(profile_index);
4412 profile_index--;
4413 } else {
4414 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004415 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004416 if (audio_device_is_digital(deviceType)) {
4417 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004418 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004419
François Gaffie11d30102018-11-02 16:09:09 +01004420 if (device_distinguishes_on_address(deviceType)) {
4421 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4422 device->toString().c_str());
4423 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4424 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004425 }
Eric Laurente552edb2014-03-10 17:42:56 -07004426 ALOGV("checkOutputsForDevice(): adding output %d", output);
4427 }
4428 }
4429
4430 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004431 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004432 return BAD_VALUE;
4433 }
Eric Laurentd4692962014-05-05 18:13:44 -07004434 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004435 // check if one opened output is not needed any more after disconnecting one device
4436 for (size_t i = 0; i < mOutputs.size(); i++) {
4437 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004438 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004439 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004440 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4441 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004442 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004443 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004444 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4445 mOutputs.keyAt(i));
4446 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004447 }
Eric Laurente552edb2014-03-10 17:42:56 -07004448 }
4449 }
Eric Laurentd4692962014-05-05 18:13:44 -07004450 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004451 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004452 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4453 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004454 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004455 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004456 "clearing direct output profile %zu on module %s",
4457 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004458 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004459 }
4460 }
4461 }
4462 }
4463 return NO_ERROR;
4464}
4465
François Gaffie11d30102018-11-02 16:09:09 +01004466status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004467 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004468 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004469{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004470 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004471
François Gaffie11d30102018-11-02 16:09:09 +01004472 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004473 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004474 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004475 }
4476
Eric Laurentd4692962014-05-05 18:13:44 -07004477 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4478 // first list already open inputs that can be routed to this device
4479 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4480 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004481 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004482 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4483 inputs.add(mInputs.keyAt(input_index));
4484 }
4485 }
4486
4487 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004488 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004489 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004490 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004491 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004492 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004493 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004494
François Gaffie11d30102018-11-02 16:09:09 +01004495 if (profile->supportsDevice(device)) {
4496 profiles.add(profile);
4497 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4498 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004499 }
4500 }
4501 }
4502
4503 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004504 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004505 return BAD_VALUE;
4506 }
4507
4508 // open inputs for matching profiles if needed. Direct inputs are also opened to
4509 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4510 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4511
Eric Laurent1c333e22014-05-20 10:48:17 -07004512 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004513
Eric Laurentd4692962014-05-05 18:13:44 -07004514 // nothing to do if one input is already opened for this profile
4515 size_t input_index;
4516 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4517 desc = mInputs.valueAt(input_index);
4518 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004519 if (audio_device_is_digital(device->type())) {
4520 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004521 }
Eric Laurentd4692962014-05-05 18:13:44 -07004522 break;
4523 }
4524 }
4525 if (input_index != mInputs.size()) {
4526 continue;
4527 }
4528
Eric Laurent3974e3b2017-12-07 17:58:43 -08004529 if (!profile->canOpenNewIo()) {
4530 ALOGW("Max Input number %u already opened for this profile %s",
4531 profile->maxOpenCount, profile->getTagName().c_str());
4532 continue;
4533 }
4534
Eric Laurentfe231122017-11-17 17:48:06 -08004535 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004536 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004537 status_t status = desc->open(nullptr,
4538 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004539 AUDIO_SOURCE_MIC,
4540 AUDIO_INPUT_FLAG_NONE,
4541 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004542
Eric Laurentcf2c0212014-07-25 16:20:43 -07004543 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004544 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004545 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004546 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004547 mpClientInterface->setParameters(input, String8(param));
4548 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004549 }
François Gaffie11d30102018-11-02 16:09:09 +01004550 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004551 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004552 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004553 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004554 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004555 }
4556
4557 if (input != 0) {
4558 addInput(input, desc);
4559 }
4560 } // endif input != 0
4561
Eric Laurentcf2c0212014-07-25 16:20:43 -07004562 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004563 ALOGW("%s could not open input for device %s", __func__,
4564 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004565 profiles.removeAt(profile_index);
4566 profile_index--;
4567 } else {
4568 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004569 if (audio_device_is_digital(device->type())) {
4570 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004571 }
Eric Laurentd4692962014-05-05 18:13:44 -07004572 ALOGV("checkInputsForDevice(): adding input %d", input);
4573 }
4574 } // end scan profiles
4575
4576 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004577 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004578 return BAD_VALUE;
4579 }
4580 } else {
4581 // Disconnect
4582 // check if one opened input is not needed any more after disconnecting one device
4583 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4584 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004585 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004586 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4587 mInputs.keyAt(input_index));
4588 inputs.add(mInputs.keyAt(input_index));
4589 }
4590 }
4591 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004592 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004593 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004594 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004595 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004596 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004597 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004598 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4599 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004600 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004601 }
4602 }
4603 }
4604 } // end disconnect
4605
4606 return NO_ERROR;
4607}
4608
4609
Eric Laurente0720872014-03-11 09:30:41 -07004610void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004611{
4612 ALOGV("closeOutput(%d)", output);
4613
Eric Laurentc75307b2015-03-17 15:29:32 -07004614 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004615 if (outputDesc == NULL) {
4616 ALOGW("closeOutput() unknown output %d", output);
4617 return;
4618 }
François Gaffie036e1e92015-03-19 10:16:24 +01004619 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004620
Eric Laurente552edb2014-03-10 17:42:56 -07004621 // look for duplicated outputs connected to the output being removed.
4622 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004623 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004624 if (dupOutputDesc->isDuplicated() &&
4625 (dupOutputDesc->mOutput1 == outputDesc ||
4626 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004627 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if (dupOutputDesc->mOutput1 == outputDesc) {
4629 outputDesc2 = dupOutputDesc->mOutput2;
4630 } else {
4631 outputDesc2 = dupOutputDesc->mOutput1;
4632 }
4633 // As all active tracks on duplicated output will be deleted,
4634 // and as they were also referenced on the other output, the reference
4635 // count for their stream type must be adjusted accordingly on
4636 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004637 const bool wasActive = outputDesc2->isActive();
4638 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4639 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004640 }
Eric Laurent733ce942017-12-07 12:18:25 -08004641 // stop() will be a no op if the output is still active but is needed in case all
4642 // active streams refcounts where cleared above
4643 if (wasActive) {
4644 outputDesc2->stop();
4645 }
Eric Laurente552edb2014-03-10 17:42:56 -07004646 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4647 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4648
4649 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004650 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004651 }
4652 }
4653
Eric Laurent05b90f82014-08-27 15:32:29 -07004654 nextAudioPortGeneration();
4655
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004656 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004657 if (index >= 0) {
4658 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004659 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004660 mAudioPatches.removeItemsAt(index);
4661 mpClientInterface->onAudioPatchListUpdate();
4662 }
4663
Eric Laurentfe231122017-11-17 17:48:06 -08004664 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004665
François Gaffie53615e22015-03-19 09:24:12 +01004666 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004667 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004668
4669 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4670 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004671 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004672 bool directOutputOpen = false;
4673 for (size_t i = 0; i < mOutputs.size(); i++) {
4674 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4675 directOutputOpen = true;
4676 break;
4677 }
4678 }
4679 if (!directOutputOpen) {
4680 ALOGV("no direct outputs open, reset MSD patch");
4681 setMsdPatch();
4682 }
4683 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004684}
4685
4686void AudioPolicyManager::closeInput(audio_io_handle_t input)
4687{
4688 ALOGV("closeInput(%d)", input);
4689
4690 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4691 if (inputDesc == NULL) {
4692 ALOGW("closeInput() unknown input %d", input);
4693 return;
4694 }
4695
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004697
François Gaffie11d30102018-11-02 16:09:09 +01004698 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004699 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004700 if (index >= 0) {
4701 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004702 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004703 mAudioPatches.removeItemsAt(index);
4704 mpClientInterface->onAudioPatchListUpdate();
4705 }
4706
Eric Laurentfe231122017-11-17 17:48:06 -08004707 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004708 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004709
François Gaffie11d30102018-11-02 16:09:09 +01004710 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4711 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004712 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4713 SoundTrigger::setCaptureState(false);
4714 }
Eric Laurente552edb2014-03-10 17:42:56 -07004715}
4716
François Gaffie11d30102018-11-02 16:09:09 +01004717SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4718 const DeviceVector &devices,
4719 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004720{
4721 SortedVector<audio_io_handle_t> outputs;
4722
François Gaffie11d30102018-11-02 16:09:09 +01004723 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004724 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004725 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004726 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004727 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004728 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4729 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004730 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004731 outputs.add(openOutputs.keyAt(i));
4732 }
4733 }
4734 return outputs;
4735}
4736
Mikhail Naganov37977152018-07-11 15:54:44 -07004737void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4738{
4739 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4740 // output is suspended before any tracks are moved to it
4741 checkA2dpSuspend();
4742 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004743 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004744 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004745 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004746 setMsdPatch();
4747 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004748}
4749
Eric Laurente0720872014-03-11 09:30:41 -07004750void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004751{
François Gaffie11d30102018-11-02 16:09:09 +01004752 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4753 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4754 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4755 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004756
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004757 // also take into account external policy-related changes: add all outputs which are
4758 // associated with policies in the "before" and "after" output vectors
4759 ALOGVV("checkOutputForStrategy(): policy related outputs");
4760 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004761 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004762 if (desc != 0 && desc->mPolicyMix != NULL) {
4763 srcOutputs.add(desc->mIoHandle);
4764 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4765 }
4766 }
4767 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004768 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004769 if (desc != 0 && desc->mPolicyMix != NULL) {
4770 dstOutputs.add(desc->mIoHandle);
4771 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4772 }
4773 }
4774
Francois Gaffie716e1432019-01-14 16:58:59 +01004775 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004776 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4777 // audio from invalidated tracks will be rendered when unmuting
4778 uint32_t maxLatency = 0;
4779 for (audio_io_handle_t srcOut : srcOutputs) {
4780 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4781 if (desc != 0 && maxLatency < desc->latency()) {
4782 maxLatency = desc->latency();
4783 }
4784 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004785 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4786 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4787 std::to_string(srcOutputs[0]).c_str(),
4788 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004789 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004790 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004791 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4792 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004793 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004794 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4795 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004796 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004797 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004798 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004799 if (source != 0){
4800 connectAudioSource(source);
4801 }
Eric Laurente552edb2014-03-10 17:42:56 -07004802 }
4803
4804 // Move effects associated to this strategy from previous output to new output
4805 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004806 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004807 }
4808 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004809 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004810 if (getStrategy((audio_stream_type_t)i) == strategy) {
4811 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004812 }
4813 }
4814 }
4815}
4816
Eric Laurente0720872014-03-11 09:30:41 -07004817void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004818{
François Gaffie2110e042015-03-24 08:41:51 +01004819 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004820 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004821 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004822 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004823 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004824 checkOutputForStrategy(STRATEGY_SONIFICATION);
4825 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004826 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004827 checkOutputForStrategy(STRATEGY_MEDIA);
4828 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004829 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004830}
4831
Eric Laurente0720872014-03-11 09:30:41 -07004832void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004833{
François Gaffie53615e22015-03-19 09:24:12 +01004834 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004835 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004836 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004837 return;
4838 }
4839
Eric Laurent3a4311c2014-03-17 12:00:47 -07004840 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004841 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4842 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4843 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004844
4845 // if suspended, restore A2DP output if:
4846 // ((SCO device is NOT connected) ||
4847 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4848 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004849 //
Eric Laurentf732e072016-08-03 19:30:28 -07004850 // if not suspended, suspend A2DP output if:
4851 // (SCO device is connected) &&
4852 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4853 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004854 //
4855 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004856 if (!isScoConnected ||
4857 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4858 AUDIO_POLICY_FORCE_BT_SCO) &&
4859 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4860 AUDIO_POLICY_FORCE_BT_SCO) &&
4861 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004862 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004863
4864 mpClientInterface->restoreOutput(a2dpOutput);
4865 mA2dpSuspended = false;
4866 }
4867 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004868 if (isScoConnected &&
4869 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4870 AUDIO_POLICY_FORCE_BT_SCO) ||
4871 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4872 AUDIO_POLICY_FORCE_BT_SCO) ||
4873 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004874 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004875
4876 mpClientInterface->suspendOutput(a2dpOutput);
4877 mA2dpSuspended = true;
4878 }
4879 }
4880}
4881
Eric Laurent97ac8712018-07-27 18:59:02 -07004882template <class IoDescriptor, class Filter>
4883sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4884 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4885{
4886 auto activeClients = desc->clientsList(true /*activeOnly*/);
4887 auto activeClientsWithRoute =
4888 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4889 active = activeClients.size() > 0;
4890 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4891 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4892 }
4893 return nullptr;
4894}
4895
4896template <class IoCollection, class Filter>
4897sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4898 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4899{
4900 sp<DeviceDescriptor> device;
4901 for (size_t i = 0; i < ioCollection.size(); i++) {
4902 auto desc = ioCollection.valueAt(i);
4903 bool active;
4904 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4905 if (active && curDevice == nullptr) {
4906 return nullptr;
4907 } else if (curDevice != nullptr) {
4908 device = curDevice;
4909 }
4910 }
4911 return device;
4912}
4913
François Gaffie11d30102018-11-02 16:09:09 +01004914DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4915 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004916{
François Gaffie11d30102018-11-02 16:09:09 +01004917 DeviceVector devices;
4918
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004919 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004920 if (index >= 0) {
4921 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4922 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004923 ALOGV("%s device %s forced by patch %d", __func__,
4924 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4925 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 }
4927 }
4928
Eric Laurent97ac8712018-07-27 18:59:02 -07004929 // Honor explicit routing requests only if no client using default routing is active on this
4930 // input: a specific app can not force routing for other apps by setting a preferred device.
4931 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004932 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004933 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004934 if (device != nullptr) {
4935 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004936 }
4937
Eric Laurente552edb2014-03-10 17:42:56 -07004938 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004939 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004940 // use device for strategy enforced audible
4941 // 2: we are in call or the strategy phone is active on the output:
4942 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004943 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004944 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004945 // 4: the strategy for enforced audible is active but not enforced on the output:
4946 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004947 // 5: the strategy accessibility is active on the output:
4948 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004949 // 6: the strategy "respectful" sonification is active on the output:
4950 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004951 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004952 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004953 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004954 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004955 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004956 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004957
4958 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4959 // with a refined rule considering mutually exclusive devices (using same backend)
4960 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004961 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004962 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004963 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004964 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004965 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004966 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004967 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01004968 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004969 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004970 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004971 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01004972 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004973 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01004974 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004975 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01004976 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004977 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01004978 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004979 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01004980 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004981 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01004982 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004983 }
4984
François Gaffie11d30102018-11-02 16:09:09 +01004985 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
4986 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004987}
4988
François Gaffie11d30102018-11-02 16:09:09 +01004989sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4990 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004991{
François Gaffie11d30102018-11-02 16:09:09 +01004992 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004993
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004994 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 if (index >= 0) {
4996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4997 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004998 ALOGV("getNewInputDevice() device %s forced by patch %d",
4999 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5000 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 }
5002 }
5003
Eric Laurent97ac8712018-07-27 18:59:02 -07005004 // Honor explicit routing requests only if no client using default routing is active on this
5005 // input: a specific app can not force routing for other apps by setting a preferred device.
5006 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005007 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5008 if (device != nullptr) {
5009 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005010 }
5011
Eric Laurentdc95a252018-04-12 12:46:56 -07005012 // If we are not in call and no client is active on this input, this methods returns
5013 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005014 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5015 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5016 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005017 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005018 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5019 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005020 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005021
Eric Laurente552edb2014-03-10 17:42:56 -07005022 return device;
5023}
5024
Eric Laurent794fde22016-03-11 09:50:45 -08005025bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5026 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005027 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005028}
5029
Eric Laurente0720872014-03-11 09:30:41 -07005030uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005031 return (uint32_t)getStrategy(stream);
5032}
5033
Eric Laurente0720872014-03-11 09:30:41 -07005034audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005035 // By checking the range of stream before calling getStrategy, we avoid
5036 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5037 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005038 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 return AUDIO_DEVICE_NONE;
5040 }
François Gaffie11d30102018-11-02 16:09:09 +01005041 DeviceVector activeDevices;
5042 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005043 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5044 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005045 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 }
Eric Laurent794fde22016-03-11 09:50:45 -08005047 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005048 DeviceVector curDevices =
5049 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5050 devices.merge(curDevices);
5051 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005052 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005053 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005054 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005055 }
5056 }
Eric Laurente552edb2014-03-10 17:42:56 -07005057 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005058
Eric Laurentb0688d62018-08-14 15:49:18 -07005059 // Favor devices selected on active streams if any to report correct device in case of
5060 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005061 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005062 devices = activeDevices;
5063 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005064 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5065 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005066 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5067 if (!speakerSafeDevices.isEmpty()) {
5068 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5069 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005070 }
François Gaffie11d30102018-11-02 16:09:09 +01005071 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005072}
5073
François Gaffie2110e042015-03-24 08:41:51 +01005074routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5075{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005076 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005077 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005078}
5079
Eric Laurent97ac8712018-07-27 18:59:02 -07005080routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005081 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005082 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005083 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005084 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005085 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005086 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005087 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005088 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005089 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005090}
5091
Eric Laurente0720872014-03-11 09:30:41 -07005092void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005093 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005094 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005095 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5096 updateDevicesAndOutputs();
5097 break;
5098 default:
5099 break;
5100 }
5101}
5102
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005103uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005104
5105 // skip beacon mute management if a dedicated TTS output is available
5106 if (mTtsOutputAvailable) {
5107 return 0;
5108 }
5109
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005110 switch(event) {
5111 case STARTING_OUTPUT:
5112 mBeaconMuteRefCount++;
5113 break;
5114 case STOPPING_OUTPUT:
5115 if (mBeaconMuteRefCount > 0) {
5116 mBeaconMuteRefCount--;
5117 }
5118 break;
5119 case STARTING_BEACON:
5120 mBeaconPlayingRefCount++;
5121 break;
5122 case STOPPING_BEACON:
5123 if (mBeaconPlayingRefCount > 0) {
5124 mBeaconPlayingRefCount--;
5125 }
5126 break;
5127 }
5128
5129 if (mBeaconMuteRefCount > 0) {
5130 // any playback causes beacon to be muted
5131 return setBeaconMute(true);
5132 } else {
5133 // no other playback: unmute when beacon starts playing, mute when it stops
5134 return setBeaconMute(mBeaconPlayingRefCount == 0);
5135 }
5136}
5137
5138uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5139 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5140 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5141 // keep track of muted state to avoid repeating mute/unmute operations
5142 if (mBeaconMuted != mute) {
5143 // mute/unmute AUDIO_STREAM_TTS on all outputs
5144 ALOGV("\t muting %d", mute);
5145 uint32_t maxLatency = 0;
5146 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005147 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005148 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005149 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005150 0 /*delay*/, AUDIO_DEVICE_NONE);
5151 const uint32_t latency = desc->latency() * 2;
5152 if (latency > maxLatency) {
5153 maxLatency = latency;
5154 }
5155 }
5156 mBeaconMuted = mute;
5157 return maxLatency;
5158 }
5159 return 0;
5160}
5161
François Gaffie11d30102018-11-02 16:09:09 +01005162DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005163{
Eric Laurent97ac8712018-07-27 18:59:02 -07005164 // Honor explicit routing requests only if all active clients have a preferred route in which
5165 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005166 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5167 if (device != nullptr) {
5168 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005169 }
5170
Eric Laurente552edb2014-03-10 17:42:56 -07005171 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005172 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5173 mDevicesForStrategy[strategy].toString().c_str());
5174 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005175 }
François Gaffie11d30102018-11-02 16:09:09 +01005176 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005177}
5178
Eric Laurente0720872014-03-11 09:30:41 -07005179void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005180{
5181 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005182 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005183 }
5184 mPreviousOutputs = mOutputs;
5185}
5186
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005187uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005188 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005189 uint32_t delayMs)
5190{
5191 // mute/unmute strategies using an incompatible device combination
5192 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5193 // if unmuting, unmute only after the specified delay
5194 if (outputDesc->isDuplicated()) {
5195 return 0;
5196 }
5197
5198 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005199 audio_devices_t deviceType = outputDesc->devices().types();
5200 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005201
5202 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005203 audio_devices_t curDeviceType =
5204 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5205 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5206 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005207 bool doMute = false;
5208
5209 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5210 doMute = true;
5211 outputDesc->mStrategyMutedByDevice[i] = true;
5212 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5213 doMute = true;
5214 outputDesc->mStrategyMutedByDevice[i] = false;
5215 }
Eric Laurent99401132014-05-07 19:48:15 -07005216 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005217 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005218 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005219 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005220 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005221 continue;
5222 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005223 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005224 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005226 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005227 if (mute) {
5228 // FIXME: should not need to double latency if volume could be applied
5229 // immediately by the audioflinger mixer. We must account for the delay
5230 // between now and the next time the audioflinger thread for this output
5231 // will process a buffer (which corresponds to one buffer size,
5232 // usually 1/2 or 1/4 of the latency).
5233 if (muteWaitMs < desc->latency() * 2) {
5234 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005235 }
5236 }
5237 }
5238 }
5239 }
5240 }
5241
Eric Laurent99401132014-05-07 19:48:15 -07005242 // temporary mute output if device selection changes to avoid volume bursts due to
5243 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005244 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005245 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5246 // temporary mute duration is conservatively set to 4 times the reported latency
5247 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5248 if (muteWaitMs < tempMuteWaitMs) {
5249 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005250 }
Eric Laurentdc462862016-07-19 12:29:53 -07005251
Eric Laurent99401132014-05-07 19:48:15 -07005252 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005253 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005254 // make sure that we do not start the temporary mute period too early in case of
5255 // delayed device change
5256 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005257 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005258 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005259 }
5260 }
5261 }
5262
Eric Laurente552edb2014-03-10 17:42:56 -07005263 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5264 if (muteWaitMs > delayMs) {
5265 muteWaitMs -= delayMs;
5266 usleep(muteWaitMs * 1000);
5267 return muteWaitMs;
5268 }
5269 return 0;
5270}
5271
François Gaffie11d30102018-11-02 16:09:09 +01005272uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5273 const DeviceVector &devices,
5274 bool force,
5275 int delayMs,
5276 audio_patch_handle_t *patchHandle,
5277 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005278{
François Gaffie11d30102018-11-02 16:09:09 +01005279 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005280 uint32_t muteWaitMs;
5281
5282 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005283 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5284 nullptr /* patchHandle */, requiresMuteCheck);
5285 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5286 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005287 return muteWaitMs;
5288 }
Eric Laurente552edb2014-03-10 17:42:56 -07005289
5290 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005291 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005292
François Gaffie11d30102018-11-02 16:09:09 +01005293 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5294 // output profile
5295 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5296 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5297 return 0;
5298 }
Eric Laurente552edb2014-03-10 17:42:56 -07005299
François Gaffie11d30102018-11-02 16:09:09 +01005300 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005301
François Gaffie11d30102018-11-02 16:09:09 +01005302 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5303
5304 if (!filteredDevices.isEmpty()) {
5305 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005306 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005307
5308 // if the outputs are not materially active, there is no need to mute.
5309 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005310 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005311 } else {
5312 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5313 muteWaitMs = 0;
5314 }
Eric Laurente552edb2014-03-10 17:42:56 -07005315
5316 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005317 // the requested device is AUDIO_DEVICE_NONE
5318 // OR the requested device is the same as current device
5319 // AND force is not specified
5320 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005321 // Doing this check here allows the caller to call setOutputDevices() without conditions
5322 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5323 !force && outputDesc->getPatchHandle() != 0) {
5324 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5325 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005326 return muteWaitMs;
5327 }
5328
François Gaffie11d30102018-11-02 16:09:09 +01005329 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005330
Eric Laurente552edb2014-03-10 17:42:56 -07005331 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005332 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005333 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005334 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005335 PatchBuilder patchBuilder;
5336 patchBuilder.addSource(outputDesc);
5337 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5338 for (const auto &filteredDevice : filteredDevices) {
5339 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005340 }
5341
François Gaffie11d30102018-11-02 16:09:09 +01005342 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005343 }
Eric Laurente552edb2014-03-10 17:42:56 -07005344
5345 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005346 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005347
5348 return muteWaitMs;
5349}
5350
Eric Laurentc75307b2015-03-17 15:29:32 -07005351status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 int delayMs,
5353 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005354{
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 ssize_t index;
5356 if (patchHandle) {
5357 index = mAudioPatches.indexOfKey(*patchHandle);
5358 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005359 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 }
5361 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005362 return INVALID_OPERATION;
5363 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5365 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005367 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 removeAudioPatch(patchDesc->mHandle);
5369 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005370 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 return status;
5372}
5373
5374status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005375 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 bool force,
5377 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005378{
5379 status_t status = NO_ERROR;
5380
Eric Laurent1f2f2232014-06-02 12:01:23 -07005381 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005382 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5383 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005384
François Gaffie11d30102018-11-02 16:09:09 +01005385 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005386 PatchBuilder patchBuilder;
5387 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005388 // AUDIO_SOURCE_HOTWORD is for internal use only:
5389 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005390 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5391 auto result = usecase;
5392 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5393 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5394 }
5395 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005397 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005398 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005399 }
5400 }
5401 return status;
5402}
5403
Eric Laurent6a94d692014-05-20 11:18:06 -07005404status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5405 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005406{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005407 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 ssize_t index;
5409 if (patchHandle) {
5410 index = mAudioPatches.indexOfKey(*patchHandle);
5411 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005412 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 }
5414 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005415 return INVALID_OPERATION;
5416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5418 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005420 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 removeAudioPatch(patchDesc->mHandle);
5422 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005423 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005424 return status;
5425}
5426
François Gaffie11d30102018-11-02 16:09:09 +01005427sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005428 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005429 audio_format_t& format,
5430 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005431 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005432{
5433 // Choose an input profile based on the requested capture parameters: select the first available
5434 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005435 //
5436 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5437 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005438
Glenn Kasten730b9262018-03-29 15:01:26 -07005439 sp<IOProfile> firstInexact;
5440 uint32_t updatedSamplingRate = 0;
5441 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5442 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005443 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005444 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005445 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005446 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005447 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005448 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005449 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005450 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005451 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005452 &channelMask /*updatedChannelMask*/,
5453 // FIXME ugly cast
5454 (audio_output_flags_t) flags,
5455 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005456 return profile;
5457 }
François Gaffie11d30102018-11-02 16:09:09 +01005458 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005459 samplingRate,
5460 &updatedSamplingRate,
5461 format,
5462 &updatedFormat,
5463 channelMask,
5464 &updatedChannelMask,
5465 // FIXME ugly cast
5466 (audio_output_flags_t) flags,
5467 false /*exactMatchRequiredForInputFlags*/)) {
5468 firstInexact = profile;
5469 }
5470
Eric Laurente552edb2014-03-10 17:42:56 -07005471 }
5472 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005473 if (firstInexact != nullptr) {
5474 samplingRate = updatedSamplingRate;
5475 format = updatedFormat;
5476 channelMask = updatedChannelMask;
5477 return firstInexact;
5478 }
Eric Laurente552edb2014-03-10 17:42:56 -07005479 return NULL;
5480}
5481
Francois Gaffie716e1432019-01-14 16:58:59 +01005482sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5483 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005484{
Eric Laurent97ac8712018-07-27 18:59:02 -07005485 // Honor explicit routing requests only if all active clients have a preferred route in which
5486 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005487 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005488 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005489 if (device != nullptr) {
5490 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005491 }
5492
François Gaffie11d30102018-11-02 16:09:09 +01005493 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005494 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005495 policyMix);
5496 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005497 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005498}
5499
Francois Gaffie716e1432019-01-14 16:58:59 +01005500sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005501{
Francois Gaffie716e1432019-01-14 16:58:59 +01005502 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5503 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5504 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5505 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005506 String8(attributes.tags + strlen("addr=")),
5507 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005508 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005509 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005510}
5511
Eric Laurente0720872014-03-11 09:30:41 -07005512float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005513 int index,
5514 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005515{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005516 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005517
5518 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5519 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5520 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5521 // the ringtone volume
5522 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5523 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5524 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5525 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5526 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5527 }
5528
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005529 // in-call: always cap volume by voice volume + some low headroom
5530 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005531 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005532 switch (stream) {
5533 case AUDIO_STREAM_SYSTEM:
5534 case AUDIO_STREAM_RING:
5535 case AUDIO_STREAM_MUSIC:
5536 case AUDIO_STREAM_ALARM:
5537 case AUDIO_STREAM_NOTIFICATION:
5538 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5539 case AUDIO_STREAM_DTMF:
5540 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005541 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005542 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005543 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005544 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005545 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005546 if (volumeDB > maxVoiceVolDb) {
5547 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5548 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5549 volumeDB = maxVoiceVolDb;
5550 }
5551 } break;
5552 default:
5553 break;
5554 }
5555 }
5556
Eric Laurente552edb2014-03-10 17:42:56 -07005557 // if a headset is connected, apply the following rules to ring tones and notifications
5558 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005559 // - always attenuate notifications volume by 6dB
5560 // - attenuate ring tones volume by 6dB unless music is not playing and
5561 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005562 // - if music is playing, always limit the volume to current music volume,
5563 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005564 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5566 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5567 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005568 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005569 AUDIO_DEVICE_OUT_USB_HEADSET |
5570 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005571 ((stream_strategy == STRATEGY_SONIFICATION)
5572 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005573 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005574 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005575 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005576 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005577 // when the phone is ringing we must consider that music could have been paused just before
5578 // by the music application and behave as if music was active if the last music track was
5579 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005580 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005581 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005582 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005583 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005584 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005585 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5586 musicDevice),
5587 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005588 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5589 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005590 if (volumeDB > minVolDB) {
5591 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005592 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005593 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005594 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5595 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5596 // on A2DP, also ensure notification volume is not too low compared to media when
5597 // intended to be played
5598 if ((volumeDB > -96.0f) &&
5599 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5600 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5601 stream, device,
5602 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5603 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5604 }
5605 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005606 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5607 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005608 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005609 }
5610 }
5611
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005612 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005613}
5614
Eric Laurent3839bc02018-07-10 18:33:34 -07005615int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5616 audio_stream_type_t srcStream,
5617 audio_stream_type_t dstStream)
5618{
5619 if (srcStream == dstStream) {
5620 return srcIndex;
5621 }
5622 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5623 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5624 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5625 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5626
5627 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5628}
5629
Eric Laurente0720872014-03-11 09:30:41 -07005630status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005631 int index,
5632 const sp<AudioOutputDescriptor>& outputDesc,
5633 audio_devices_t device,
5634 int delayMs,
5635 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005636{
Eric Laurente552edb2014-03-10 17:42:56 -07005637 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005638 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005639 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005641 return NO_ERROR;
5642 }
François Gaffie2110e042015-03-24 08:41:51 +01005643 audio_policy_forced_cfg_t forceUseForComm =
5644 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005645 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005646 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5647 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005648 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005649 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005650 return INVALID_OPERATION;
5651 }
5652
Eric Laurentc75307b2015-03-17 15:29:32 -07005653 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005654 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005655 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005656
Eric Laurentffbc80f2015-03-18 18:30:19 -07005657 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005658 if (outputDesc->isFixedVolume(device) ||
5659 // Force VoIP volume to max for bluetooth SCO
5660 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5661 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005662 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005663 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005664
Eric Laurentffbc80f2015-03-18 18:30:19 -07005665 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005666
Eric Laurent3b73df72014-03-11 09:06:29 -07005667 if (stream == AUDIO_STREAM_VOICE_CALL ||
5668 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005669 float voiceVolume;
5670 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005671 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005672 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005673 } else {
5674 voiceVolume = 1.0;
5675 }
5676
Eric Laurent18fba842016-03-31 14:41:26 -07005677 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005678 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5679 mLastVoiceVolume = voiceVolume;
5680 }
5681 }
5682
5683 return NO_ERROR;
5684}
5685
Eric Laurentc75307b2015-03-17 15:29:32 -07005686void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5687 audio_devices_t device,
5688 int delayMs,
5689 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005690{
Eric Laurentc75307b2015-03-17 15:29:32 -07005691 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005692
Eric Laurent794fde22016-03-11 09:50:45 -08005693 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005694 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005695 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005696 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005697 device,
5698 delayMs,
5699 force);
5700 }
5701}
5702
Eric Laurente0720872014-03-11 09:30:41 -07005703void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005704 bool on,
5705 const sp<AudioOutputDescriptor>& outputDesc,
5706 int delayMs,
5707 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005708{
Eric Laurent72249d52015-06-08 11:12:15 -07005709 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5710 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005711 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005712 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005713 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005714 }
5715 }
5716}
5717
Eric Laurente0720872014-03-11 09:30:41 -07005718void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005719 bool on,
5720 const sp<AudioOutputDescriptor>& outputDesc,
5721 int delayMs,
5722 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005723{
Eric Laurente552edb2014-03-10 17:42:56 -07005724 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005725 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005726 }
5727
Eric Laurentc75307b2015-03-17 15:29:32 -07005728 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5729 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005730
5731 if (on) {
5732 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005733 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005734 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005735 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005736 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005737 }
5738 }
5739 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5740 outputDesc->mMuteCount[stream]++;
5741 } else {
5742 if (outputDesc->mMuteCount[stream] == 0) {
5743 ALOGV("setStreamMute() unmuting non muted stream!");
5744 return;
5745 }
5746 if (--outputDesc->mMuteCount[stream] == 0) {
5747 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005748 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005749 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005750 device,
5751 delayMs);
5752 }
5753 }
5754}
5755
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005756audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5757{
5758 // flags to stream type mapping
5759 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5760 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5761 }
5762 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5763 return AUDIO_STREAM_BLUETOOTH_SCO;
5764 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005765 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5766 return AUDIO_STREAM_TTS;
5767 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005768
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005769 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005770}
Eric Laurente83b55d2014-11-14 10:06:21 -08005771
François Gaffie53615e22015-03-19 09:24:12 +01005772bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5773{
Eric Laurente83b55d2014-11-14 10:06:21 -08005774 // has flags that map to a strategy?
5775 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5776 return true;
5777 }
5778
5779 // has known usage?
5780 switch (paa->usage) {
5781 case AUDIO_USAGE_UNKNOWN:
5782 case AUDIO_USAGE_MEDIA:
5783 case AUDIO_USAGE_VOICE_COMMUNICATION:
5784 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5785 case AUDIO_USAGE_ALARM:
5786 case AUDIO_USAGE_NOTIFICATION:
5787 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5788 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5789 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5790 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5791 case AUDIO_USAGE_NOTIFICATION_EVENT:
5792 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5793 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5794 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5795 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005796 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005797 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005798 break;
5799 default:
5800 return false;
5801 }
5802 return true;
5803}
5804
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005805bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005806 routing_strategy strategy, uint32_t inPastMs,
5807 nsecs_t sysTime) const
5808{
5809 if ((sysTime == 0) && (inPastMs != 0)) {
5810 sysTime = systemTime();
5811 }
Eric Laurent794fde22016-03-11 09:50:45 -08005812 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005813 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005814 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005815 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5816 return true;
5817 }
5818 }
5819 return false;
5820}
5821
François Gaffie11d30102018-11-02 16:09:09 +01005822bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5823 routing_strategy strategy, uint32_t inPastMs,
5824 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005825{
5826 for (size_t i = 0; i < mOutputs.size(); i++) {
5827 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5828 if (outputDesc->sharesHwModuleWith(desc)
5829 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5830 return true;
5831 }
5832 }
5833 return false;
5834}
5835
François Gaffie2110e042015-03-24 08:41:51 +01005836audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5837{
5838 return mEngine->getForceUse(usage);
5839}
5840
5841bool AudioPolicyManager::isInCall()
5842{
5843 return isStateInCall(mEngine->getPhoneState());
5844}
5845
5846bool AudioPolicyManager::isStateInCall(int state)
5847{
5848 return is_state_in_call(state);
5849}
5850
Eric Laurentd60560a2015-04-10 11:31:20 -07005851void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5852{
5853 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005854 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5855 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5856 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5857 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005858 }
5859 }
5860
5861 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5862 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5863 bool release = false;
5864 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5865 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5866 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5867 source->ext.device.type == deviceDesc->type()) {
5868 release = true;
5869 }
5870 }
5871 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5872 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5873 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5874 sink->ext.device.type == deviceDesc->type()) {
5875 release = true;
5876 }
5877 }
5878 if (release) {
5879 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5880 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5881 }
5882 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005883
5884 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005885}
5886
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005887void AudioPolicyManager::modifySurroundFormats(
5888 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005889 std::unordered_set<audio_format_t> enforcedSurround(
5890 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005891 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5892 for (const auto& pair : mConfig.getSurroundFormats()) {
5893 allSurround.insert(pair.first);
5894 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5895 }
Phil Burk09bc4612016-02-24 15:58:15 -08005896
5897 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5898 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005899 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005900 // This is the resulting set of formats depending on the surround mode:
5901 // 'all surround' = allSurround
5902 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5903 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5904 // 'manual surround' = mManualSurroundFormats
5905 // AUTO: formats v 'enforced surround'
5906 // ALWAYS: formats v 'all surround' v 'enforced surround'
5907 // NEVER: formats ^ 'non-surround'
5908 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005909
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005910 std::unordered_set<audio_format_t> formatSet;
5911 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5912 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005913 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005914 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005915 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005916 formatSet.insert(*formatIter);
5917 }
5918 }
5919 } else {
5920 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5921 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005922 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005923
jiabin81772902018-04-02 17:52:27 -07005924 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005925 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005926 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5927 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5928 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005929 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005930 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5931 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5932 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005933 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005934 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005935 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005936 for (const auto& format : formatSet) {
5937 formatsPtr->push(format);
5938 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005939}
5940
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005941void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005942 ChannelsVector &channelMasks = *channelMasksPtr;
5943 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5944 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5945
5946 // If NEVER, then remove support for channelMasks > stereo.
5947 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5948 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5949 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5950 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5951 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5952 channelMasks.removeAt(maskIndex);
5953 } else {
5954 maskIndex++;
5955 }
5956 }
jiabin81772902018-04-02 17:52:27 -07005957 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5958 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5959 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005960 bool supports5dot1 = false;
5961 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005962 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005963 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5964 supports5dot1 = true;
5965 break;
5966 }
5967 }
5968 // If not then add 5.1 support.
5969 if (!supports5dot1) {
5970 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005971 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005972 }
Phil Burk09bc4612016-02-24 15:58:15 -08005973 }
5974}
5975
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005976void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005977 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005978 AudioProfileVector &profiles)
5979{
5980 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005981 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005982
François Gaffie112b0af2015-11-19 16:13:25 +01005983 // Format MUST be checked first to update the list of AudioProfile
5984 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005985 reply = mpClientInterface->getParameters(
5986 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005987 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005988 AudioParameter repliedParameters(reply);
5989 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005990 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005991 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5992 return;
5993 }
Phil Burk09bc4612016-02-24 15:58:15 -08005994 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005995 if (device == AUDIO_DEVICE_OUT_HDMI
5996 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005997 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005998 }
Phil Burk09bc4612016-02-24 15:58:15 -08005999 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006000 }
François Gaffie112b0af2015-11-19 16:13:25 +01006001
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006002 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006003 ChannelsVector channelMasks;
6004 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006005 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006006 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006007
6008 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006009 reply = mpClientInterface->getParameters(
6010 ioHandle,
6011 requestedParameters.toString() + ";" +
6012 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006013 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006014 AudioParameter repliedParameters(reply);
6015 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006016 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006017 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006018 }
6019 }
6020 if (profiles.hasDynamicChannelsFor(format)) {
6021 reply = mpClientInterface->getParameters(ioHandle,
6022 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006023 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006024 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006025 AudioParameter repliedParameters(reply);
6026 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006027 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006028 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006029 if (device == AUDIO_DEVICE_OUT_HDMI
6030 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006031 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006032 }
François Gaffie112b0af2015-11-19 16:13:25 +01006033 }
6034 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006035 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006036 }
6037}
Eric Laurentd60560a2015-04-10 11:31:20 -07006038
Mikhail Naganovdc769682018-05-04 15:34:08 -07006039status_t AudioPolicyManager::installPatch(const char *caller,
6040 audio_patch_handle_t *patchHandle,
6041 AudioIODescriptorInterface *ioDescriptor,
6042 const struct audio_patch *patch,
6043 int delayMs)
6044{
6045 ssize_t index = mAudioPatches.indexOfKey(
6046 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6047 *patchHandle : ioDescriptor->getPatchHandle());
6048 sp<AudioPatch> patchDesc;
6049 status_t status = installPatch(
6050 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6051 if (status == NO_ERROR) {
6052 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6053 }
6054 return status;
6055}
6056
6057status_t AudioPolicyManager::installPatch(const char *caller,
6058 ssize_t index,
6059 audio_patch_handle_t *patchHandle,
6060 const struct audio_patch *patch,
6061 int delayMs,
6062 uid_t uid,
6063 sp<AudioPatch> *patchDescPtr)
6064{
6065 sp<AudioPatch> patchDesc;
6066 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6067 if (index >= 0) {
6068 patchDesc = mAudioPatches.valueAt(index);
6069 afPatchHandle = patchDesc->mAfPatchHandle;
6070 }
6071
6072 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6073 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6074 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6075 if (status == NO_ERROR) {
6076 if (index < 0) {
6077 patchDesc = new AudioPatch(patch, uid);
6078 addAudioPatch(patchDesc->mHandle, patchDesc);
6079 } else {
6080 patchDesc->mPatch = *patch;
6081 }
6082 patchDesc->mAfPatchHandle = afPatchHandle;
6083 if (patchHandle) {
6084 *patchHandle = patchDesc->mHandle;
6085 }
6086 nextAudioPortGeneration();
6087 mpClientInterface->onAudioPatchListUpdate();
6088 }
6089 if (patchDescPtr) *patchDescPtr = patchDesc;
6090 return status;
6091}
6092
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006093} // namespace android