blob: 0d9663aa1c2da49af214b099e1512eae1a84c023 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080084 const char *device_name,
85 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -070086{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080087 status_t status = setDeviceConnectionStateInt(device, state, device_address,
88 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080089 nextAudioPortGeneration();
90 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080091}
92
François Gaffie11d30102018-11-02 16:09:09 +010093void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
94 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020095{
François Gaffie11d30102018-11-02 16:09:09 +010096 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020097 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070098 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010099 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200100 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
101}
102
François Gaffie11d30102018-11-02 16:09:09 +0100103status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800104 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800105 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 const char *device_name,
107 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800109 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
110 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700111
112 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100113 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700114
François Gaffie11d30102018-11-02 16:09:09 +0100115 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800116 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100117 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
118 if (device == 0) {
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100123 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700124 SortedVector <audio_io_handle_t> outputs;
125
François Gaffie11d30102018-11-02 16:09:09 +0100126 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127
Eric Laurente552edb2014-03-10 17:42:56 -0700128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 switch (state)
132 {
133 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100136 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700137 return INVALID_OPERATION;
138 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800139 ALOGV("%s() connecting device %s format %x",
140 __func__, device->toString().c_str(), encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // register new device as available
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800143 index = mAvailableOutputDevices.add(device);
144 if (index >= 0) {
145 sp<HwModule> module = mHwModules.getModuleForDevice(device, encodedFormat);
146 if (module == 0) {
147 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
148 device->toString().c_str());
149 mAvailableOutputDevices.remove(device);
150 return INVALID_OPERATION;
151 }
152 ALOGV("setDeviceConnectionState() module name=%s", module->getName());
153 mAvailableOutputDevices[index]->attach(module);
154 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100160 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200161
François Gaffie11d30102018-11-02 16:09:09 +0100162 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
163 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200164
Francois Gaffie716e1432019-01-14 16:58:59 +0100165 mHwModules.cleanUpForDevice(device);
166
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700168 return INVALID_OPERATION;
169 }
François Gaffie2110e042015-03-24 08:41:51 +0100170 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100171 mEngine->setDeviceConnectionState(device, state);
François Gaffie2110e042015-03-24 08:41:51 +0100172
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 // outputs should never be empty here
174 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
175 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100176 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100182 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700183 return INVALID_OPERATION;
184 }
185
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100189 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100192 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
François Gaffie11d30102018-11-02 16:09:09 +0100194 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100195
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800196 // Reset active device codec
197 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
198
François Gaffie2110e042015-03-24 08:41:51 +0100199 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100200 mEngine->setDeviceConnectionState(device, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700201 } break;
202
203 default:
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return BAD_VALUE;
206 }
207
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 checkForDeviceAndOutputChanges([&]() {
209 // outputs must be closed after checkOutputForAllStrategies() is executed
210 if (!outputs.isEmpty()) {
211 for (audio_io_handle_t output : outputs) {
212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100213 // close unused outputs after device disconnection or direct outputs that have
214 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
216 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
217 (desc->mDirectOpenCount == 0))) {
218 closeOutput(output);
219 }
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
222 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700224 return false;
225 });
Eric Laurente552edb2014-03-10 17:42:56 -0700226
Eric Laurent87ffa392015-05-22 10:32:38 -0700227 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100228 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
229 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 }
François Gaffie11d30102018-11-02 16:09:09 +0100231 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700232 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
234 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700236 // do not force device change on duplicated output because if device is 0, it will
237 // also force a device 0 for the two outputs it is duplicated to which may override
238 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100239 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100240 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100241 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 // always force when disconnecting (a non-duplicated device)
243 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100244 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700245 }
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
247
Eric Laurentd60560a2015-04-10 11:31:20 -0700248 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100249 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700250 }
251
Eric Laurent72aa32f2014-05-30 18:51:48 -0700252 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700253 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700254 } // end if is output device
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700258 SortedVector <audio_io_handle_t> inputs;
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 switch (state)
262 {
263 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return INVALID_OPERATION;
268 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800269 sp<HwModule> module = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
270 if (module == NULL) {
271 ALOGW("setDeviceConnectionState(): could not find HW module for device %s",
272 device->toString().c_str());
273 return INVALID_OPERATION;
274 }
275
François Gaffie44481e72016-04-20 07:49:57 +0200276 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
277 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100278 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200279
François Gaffie11d30102018-11-02 16:09:09 +0100280 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
281 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100282
283 mHwModules.cleanUpForDevice(device);
284
Eric Laurentd4692962014-05-05 18:13:44 -0700285 return INVALID_OPERATION;
286 }
287
Francois Gaffie716e1432019-01-14 16:58:59 +0100288 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 return NO_MEMORY;
290 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800291
François Gaffie2110e042015-03-24 08:41:51 +0100292 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100293 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700294 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700295
296 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700297 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100299 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700300 return INVALID_OPERATION;
301 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700302
François Gaffie11d30102018-11-02 16:09:09 +0100303 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700304
305 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100306 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700307
François Gaffie11d30102018-11-02 16:09:09 +0100308 checkInputsForDevice(device, state, inputs);
309 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
François Gaffie2110e042015-03-24 08:41:51 +0100311 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100312 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700313 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700314
315 default:
François Gaffie11d30102018-11-02 16:09:09 +0100316 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 return BAD_VALUE;
318 }
319
Eric Laurentd4692962014-05-05 18:13:44 -0700320 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700321 // As the input device list can impact the output device selection, update
322 // getDeviceForStrategy() cache
323 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700324
Eric Laurent87ffa392015-05-22 10:32:38 -0700325 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
327 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 }
329
Eric Laurentd60560a2015-04-10 11:31:20 -0700330 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100331 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700332 }
333
Eric Laurentb52c1522014-05-20 11:27:36 -0700334 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700335 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700337
François Gaffie11d30102018-11-02 16:09:09 +0100338 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700339 return BAD_VALUE;
340}
341
Eric Laurente0720872014-03-11 09:30:41 -0700342audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100343 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700344{
Eric Laurent634b7142016-04-20 13:48:02 -0700345 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800346 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
347 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700348 (strlen(device_address) != 0)/*matchAddress*/);
349
350 if (devDesc == 0) {
351 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
352 device, device_address);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
354 }
François Gaffie53615e22015-03-19 09:24:12 +0100355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100363 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
Eric Laurent634b7142016-04-20 13:48:02 -0700366
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800367 return (deviceVector->getDevice(
368 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800370}
371
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800372status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
373 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800374 const char *device_name,
375 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376{
377 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700378 String8 reply;
379 AudioParameter param;
380 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800382 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
383 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800384
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800385 // connect/disconnect only 1 device at a time
386 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Check if the device is currently connected
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800389 DeviceVector availableDevices = getAvailableOutputDevices();
390 DeviceVector deviceList = availableDevices.getDevicesFromTypeMask(device);
391 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800392 // Nothing to do: device is not connected
393 return NO_ERROR;
394 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800395 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800396
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700397 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800398 // configure codecs.
399 // Handle two specific cases by sending a set parameter to
400 // configure A2DP codecs. No need to toggle device state.
401 // Case 1: A2DP active device switches from primary to primary
402 // module
403 // Case 2: A2DP device config changes on primary module.
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700404 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800405 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
406 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
407 if (availablePrimaryOutputDevices().contains(devDesc) &&
408 (module != 0 && module->getHandle() == primaryHandle)) {
409 reply = mpClientInterface->getParameters(
410 AUDIO_IO_HANDLE_NONE,
411 String8(AudioParameter::keyReconfigA2dpSupported));
412 AudioParameter repliedParameters(reply);
413 repliedParameters.getInt(
414 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
415 if (isReconfigA2dpSupported) {
416 const String8 key(AudioParameter::keyReconfigA2dp);
417 param.add(key, String8("true"));
418 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
419 devDesc->setEncodedFormat(encodedFormat);
420 return NO_ERROR;
421 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700422 }
423 }
424
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800425 // Toggle the device state: UNAVAILABLE -> AVAILABLE
426 // This will force reading again the device configuration
427 status = setDeviceConnectionState(device,
428 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800429 device_address, device_name,
430 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 if (status != NO_ERROR) {
432 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
433 status);
434 return status;
435 }
436
437 status = setDeviceConnectionState(device,
438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800439 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800440 if (status != NO_ERROR) {
441 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
442 status);
443 return status;
444 }
445
446 return NO_ERROR;
447}
448
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800449status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
450 std::vector<audio_format_t> *formats)
451{
452 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
453 char *tok = NULL, *saveptr;
454 status_t status = NO_ERROR;
455 char encoding_formats_list[PROPERTY_VALUE_MAX];
456 audio_format_t format = AUDIO_FORMAT_DEFAULT;
457 // FIXME This list should not come from a property but the supported encoded
458 // formats of declared A2DP devices in primary module
459 property_get("persist.bluetooth.a2dp_offload.cap", encoding_formats_list, "");
460 tok = strtok_r(encoding_formats_list, "-", &saveptr);
461 for (;tok != NULL; tok = strtok_r(NULL, "-", &saveptr)) {
462 if (strcmp(tok, "sbc") == 0) {
463 ALOGV("%s: SBC offload supported\n",__func__);
464 format = AUDIO_FORMAT_SBC;
465 } else if (strcmp(tok, "aptx") == 0) {
466 ALOGV("%s: APTX offload supported\n",__func__);
467 format = AUDIO_FORMAT_APTX;
468 } else if (strcmp(tok, "aptxhd") == 0) {
469 ALOGV("%s: APTX HD offload supported\n",__func__);
470 format = AUDIO_FORMAT_APTX_HD;
471 } else if (strcmp(tok, "ldac") == 0) {
472 ALOGV("%s: LDAC offload supported\n",__func__);
473 format = AUDIO_FORMAT_LDAC;
474 } else if (strcmp(tok, "aac") == 0) {
475 ALOGV("%s: AAC offload supported\n",__func__);
476 format = AUDIO_FORMAT_AAC;
477 } else {
478 ALOGE("%s: undefined token - %s\n",__func__, tok);
479 continue;
480 }
481 formats->push_back(format);
482 }
483 return status;
484}
485
François Gaffie11d30102018-11-02 16:09:09 +0100486uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487{
488 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100489 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700490 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700491
François Gaffie11d30102018-11-02 16:09:09 +0100492 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700493 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700494 }
François Gaffie11d30102018-11-02 16:09:09 +0100495 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
496
Francois Gaffie716e1432019-01-14 16:58:59 +0100497 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffie9eb18552018-11-05 10:33:26 +0100498 auto txSourceDevice = getDeviceAndMixForAttributes(attr);
499 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100501 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700502
503 // release existing RX patch if any
504 if (mCallRxPatch != 0) {
505 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
506 mCallRxPatch.clear();
507 }
508 // release TX patch if any
509 if (mCallTxPatch != 0) {
510 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
511 mCallTxPatch.clear();
512 }
513
François Gaffie9eb18552018-11-05 10:33:26 +0100514 auto telephonyRxModule =
515 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
516 auto telephonyTxModule =
517 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
518 // retrieve Rx Source and Tx Sink device descriptors
519 sp<DeviceDescriptor> rxSourceDevice =
520 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
521 String8(),
522 AUDIO_FORMAT_DEFAULT);
523 sp<DeviceDescriptor> txSinkDevice =
524 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
525 String8(),
526 AUDIO_FORMAT_DEFAULT);
527
528 // RX and TX Telephony device are declared by Primary Audio HAL
529 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
530 (telephonyRxModule->getHalVersionMajor() >= 3)) {
531 if (rxSourceDevice == 0 || txSinkDevice == 0) {
532 // RX / TX Telephony device(s) is(are) not currently available
533 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
534 return muteWaitMs;
535 }
536 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
537 // route between telephony RX to Sink device and Source device to telephony TX
538 const auto &primaryModule = telephonyRxModule;
539 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
540 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
541 } else {
542 // If the RX device is on the primary HW module, then use legacy routing method for
543 // voice calls via setOutputDevice() on primary output.
544 // Otherwise, create two audio patches for TX and RX path.
545 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
546 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547 // If the TX device is also on the primary HW module, setOutputDevice() will take care
548 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100549 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
550 (txSinkDevice != 0);
551 }
552 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
553 // Otherwise, create two audio patches for TX and RX path.
554 if (!createRxPatch) {
555 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700556 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100557 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
François Gaffie9eb18552018-11-05 10:33:26 +0100558 ALOG_ASSERT(createTxPatch, "No Tx Patch will be created, nor legacy routing done");
Eric Laurentc2730ba2014-07-20 15:47:07 -0700559 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700560 if (createTxPatch) { // create TX path audio patch
François Gaffie9eb18552018-11-05 10:33:26 +0100561 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800562 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700563
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800564 return muteWaitMs;
565}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700566
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800567sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100568 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700569 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700570
François Gaffie11d30102018-11-02 16:09:09 +0100571 if (device == nullptr) {
572 return nullptr;
573 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800574 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100575 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800576 addSource(mAvailableInputDevices.getDevice(
577 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800578 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100579 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800580 addSink(mAvailableOutputDevices.getDevice(
581 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800582 }
583
François Gaffie11d30102018-11-02 16:09:09 +0100584 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
585 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800586 device : mAvailableOutputDevices.getDevice(
587 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100588 SortedVector<audio_io_handle_t> outputs =
589 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
590 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800591 // request to reuse existing output stream if one is already opened to reach the target device
592 if (output != AUDIO_IO_HANDLE_NONE) {
593 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100594 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
595 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700596 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800597 }
598
599 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700600 // terminate active capture if on the same HW module as the call TX source device
601 // FIXME: would be better to refine to only inputs whose profile connects to the
602 // call TX device but this information is not in the audio patch and logic here must be
603 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800604 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100605 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700606 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700607 }
608 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurentdc462862016-07-19 12:29:53 -0700610
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800611 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700612 status_t status = mpClientInterface->createAudioPatch(
613 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800614 ALOGW_IF(status != NO_ERROR,
615 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
616 sp<AudioPatch> audioPatch;
617 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700618 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800619 audioPatch->mAfPatchHandle = afPatchHandle;
620 audioPatch->mUid = mUidCached;
621 }
622 return audioPatch;
623}
624
Mikhail Naganovdc769682018-05-04 15:34:08 -0700625sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100626 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700627 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800628 ALOG_ASSERT(!deviceList.isEmpty(),
629 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700630 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700631}
632
Mikhail Naganov100f0122018-11-29 11:22:16 -0800633audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
634 const DeviceVector& devices, const char *moduleId) const {
635 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
636 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
637}
638
639bool AudioPolicyManager::isDeviceOfModule(
640 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
641 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
642 if (module != 0) {
643 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
644 .indexOf(devDesc) != NAME_NOT_FOUND
645 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
646 .indexOf(devDesc) != NAME_NOT_FOUND;
647 }
648 return false;
649}
650
Eric Laurente0720872014-03-11 09:30:41 -0700651void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700652{
653 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100654 // store previous phone state for management of sonification strategy below
655 int oldState = mEngine->getPhoneState();
656
657 if (mEngine->setPhoneState(state) != NO_ERROR) {
658 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700659 return;
660 }
François Gaffie2110e042015-03-24 08:41:51 +0100661 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700662 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700663 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700664 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800665 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700666 }
667
François Gaffie2110e042015-03-24 08:41:51 +0100668 /**
669 * Switching to or from incall state or switching between telephony and VoIP lead to force
670 * routing command.
671 */
672 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
673 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700674
675 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700676 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700677
Eric Laurente552edb2014-03-10 17:42:56 -0700678 int delayMs = 0;
679 if (isStateInCall(state)) {
680 nsecs_t sysTime = systemTime();
681 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700682 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700683 // mute media and sonification strategies and delay device switch by the largest
684 // latency of any output where either strategy is active.
685 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100686 if ((isStrategyActive(desc, STRATEGY_MEDIA,
687 SONIFICATION_HEADSET_MUSIC_DELAY,
688 sysTime) ||
689 isStrategyActive(desc, STRATEGY_SONIFICATION,
690 SONIFICATION_HEADSET_MUSIC_DELAY,
691 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700692 (delayMs < (int)desc->latency()*2)) {
693 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700695 setStrategyMute(STRATEGY_MEDIA, true, desc);
696 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700697 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700698 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
699 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700700 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
701 }
702 }
703
Eric Laurent87ffa392015-05-22 10:32:38 -0700704 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100705 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100707 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700708 // force routing command to audio hardware when ending call
709 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100710 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
711 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700712 }
Eric Laurente552edb2014-03-10 17:42:56 -0700713
Eric Laurent87ffa392015-05-22 10:32:38 -0700714 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100715 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700716 } else if (oldState == AUDIO_MODE_IN_CALL) {
717 if (mCallRxPatch != 0) {
718 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
719 mCallRxPatch.clear();
720 }
721 if (mCallTxPatch != 0) {
722 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
723 mCallTxPatch.clear();
724 }
François Gaffie11d30102018-11-02 16:09:09 +0100725 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700726 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100727 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700729 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700730
731 // reevaluate routing on all outputs in case tracks have been started during the call
732 for (size_t i = 0; i < mOutputs.size(); i++) {
733 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100734 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700735 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100736 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700737 }
738 }
739
Eric Laurente552edb2014-03-10 17:42:56 -0700740 if (isStateInCall(state)) {
741 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700742 // force reevaluating accessibility routing when call starts
743 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 }
745
746 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 if (state == AUDIO_MODE_RINGTONE &&
748 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700749 mLimitRingtoneVolume = true;
750 } else {
751 mLimitRingtoneVolume = false;
752 }
753}
754
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700755audio_mode_t AudioPolicyManager::getPhoneState() {
756 return mEngine->getPhoneState();
757}
758
Eric Laurente0720872014-03-11 09:30:41 -0700759void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100760 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700761{
François Gaffie2110e042015-03-24 08:41:51 +0100762 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700763 if (config == mEngine->getForceUse(usage)) {
764 return;
765 }
Eric Laurente552edb2014-03-10 17:42:56 -0700766
François Gaffie2110e042015-03-24 08:41:51 +0100767 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
768 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
769 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700770 }
François Gaffie2110e042015-03-24 08:41:51 +0100771 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
772 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
773 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700774
775 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700776 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800777
Eric Laurentdc462862016-07-19 12:29:53 -0700778 //FIXME: workaround for truncated touch sounds
779 // to be removed when the problem is handled by system UI
780 uint32_t delayMs = 0;
781 uint32_t waitMs = 0;
782 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
783 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
784 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700785 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100786 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
787 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700788 }
Eric Laurente552edb2014-03-10 17:42:56 -0700789 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700790 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100791 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700792 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffiea807ef92018-11-05 10:44:33 +0100793 // As done in setDeviceConnectionState, we could also fix default device issue by
794 // preventing the force re-routing in case of default dev that distinguishes on address.
795 // Let's give back to engine full device choice decision however.
François Gaffie11d30102018-11-02 16:09:09 +0100796 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700797 }
François Gaffie11d30102018-11-02 16:09:09 +0100798 if (forceVolumeReeval && !newDevices.isEmpty()) {
799 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700800 }
801 }
802
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800803 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100804 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700805 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100806 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800807 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700808 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800809 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700810 }
Eric Laurente552edb2014-03-10 17:42:56 -0700811 }
Eric Laurente552edb2014-03-10 17:42:56 -0700812}
813
Eric Laurente0720872014-03-11 09:30:41 -0700814void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700815{
816 ALOGV("setSystemProperty() property %s, value %s", property, value);
817}
818
Michael Chana94fbb22018-04-24 14:31:19 +1000819// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
820// search to profiles for direct outputs.
821sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100822 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000823 uint32_t samplingRate,
824 audio_format_t format,
825 audio_channel_mask_t channelMask,
826 audio_output_flags_t flags,
827 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700828{
Michael Chana94fbb22018-04-24 14:31:19 +1000829 if (directOnly) {
830 // only retain flags that will drive the direct output profile selection
831 // if explicitly requested
832 static const uint32_t kRelevantFlags =
833 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
834 AUDIO_OUTPUT_FLAG_VOIP_RX);
835 flags =
836 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
837 }
Eric Laurent861a6282015-05-18 15:40:16 -0700838
839 sp<IOProfile> profile;
840
Mikhail Naganovd4120142017-12-06 15:49:22 -0800841 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800842 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100843 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700844 samplingRate, NULL /*updatedSamplingRate*/,
845 format, NULL /*updatedFormat*/,
846 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700847 flags)) {
848 continue;
849 }
850 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100851 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700852 continue;
853 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800854 // reject profiles if connected device does not support codec
855 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
856 continue;
857 }
Michael Chana94fbb22018-04-24 14:31:19 +1000858 if (!directOnly) return curProfile;
859 // when searching for direct outputs, if several profiles are compatible, give priority
860 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100861 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700862 continue;
863 }
864 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100865 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700866 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700867 }
Eric Laurente552edb2014-03-10 17:42:56 -0700868 }
869 }
Eric Laurent861a6282015-05-18 15:40:16 -0700870 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700871}
872
Eric Laurentf4e63452017-11-06 19:31:46 +0000873audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700874{
Eric Laurent3b73df72014-03-11 09:06:29 -0700875 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100876 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800877
878 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
879 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
880 // format, flags, etc. This may result in some discrepancy for functions that utilize
881 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
882 // and AudioSystem::getOutputSamplingRate().
883
François Gaffie11d30102018-11-02 16:09:09 +0100884 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
885 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700886
François Gaffie11d30102018-11-02 16:09:09 +0100887 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
888 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000889 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700890}
891
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700892status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
893 const audio_attributes_t *srcAttr,
894 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700895{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700896 if (srcAttr != NULL) {
897 if (!isValidAttributes(srcAttr)) {
898 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
899 __func__,
900 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
901 srcAttr->tags);
902 return BAD_VALUE;
903 }
904 *dstAttr = *srcAttr;
905 } else {
906 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
907 ALOGE("%s: invalid stream type", __func__);
908 return BAD_VALUE;
909 }
910 stream_type_to_audio_attributes(srcStream, dstAttr);
911 }
912 return NO_ERROR;
913}
914
915status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
916 audio_io_handle_t *output,
917 audio_session_t session,
918 const audio_attributes_t *attr,
919 audio_stream_type_t *stream,
920 uid_t uid,
921 const audio_config_t *config,
922 audio_output_flags_t *flags,
923 audio_port_handle_t *selectedDeviceId)
924{
François Gaffie11d30102018-11-02 16:09:09 +0100925 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700926 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100927 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100928 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100929 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700930
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700931 status_t status = getAudioAttributes(resultAttr, attr, *stream);
932 if (status != NO_ERROR) {
933 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700934 }
935
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700936 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700937 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700938 __func__,
939 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100940 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700941
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700942 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700943
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700944 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700945
Scott Randolph7b1fd232018-06-18 15:33:03 -0700946 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100947 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
948 if (requestedDevice != nullptr) {
949 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700950 } else {
951 // If no explict route, is there a matching dynamic policy that applies?
952 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700953 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700954 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
955 if (!audio_has_proportional_frames(config->format)) {
956 return BAD_VALUE;
957 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700958 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700959 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700960 AudioMix *mix = desc->mPolicyMix;
961 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800962 mAvailableOutputDevices.getDevice(
963 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700964 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700965 ALOGV("%s returns output %d", __func__, *output);
966 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700967 }
968
969 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700970 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
971 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700972 return BAD_VALUE;
973 }
François Gaffie11d30102018-11-02 16:09:09 +0100974 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700975 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700976
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700977 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200978 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700979 }
980
Nadav Barb2f18162018-07-18 13:01:53 +0300981 // Set incall music only if device was explicitly set, and fallback to the device which is
982 // chosen by the engine if not.
983 // FIXME: provide a more generic approach which is not device specific and move this back
984 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200985 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100986 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700987 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300988 audio_is_linear_pcm(config->format) &&
989 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100990 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300991 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
992 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700993 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100994 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300995 }
996 }
997
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700998 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800999 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +01001000 __func__,
1001 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001002
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001003 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001004 if (!msdDevices.isEmpty()) {
1005 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001006 sp<DeviceDescriptor> deviceDesc =
1007 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01001008 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
1009 ALOGV("%s() Using MSD devices %s instead of device %s",
1010 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
1011 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001012 } else {
1013 *output = AUDIO_IO_HANDLE_NONE;
1014 }
1015 }
François Gaffie11d30102018-11-02 16:09:09 +01001016 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001017 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01001018 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001019 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001020 if (*output == AUDIO_IO_HANDLE_NONE) {
1021 return INVALID_OPERATION;
1022 }
Paul McLeanaa981192015-03-21 09:55:15 -07001023
François Gaffie11d30102018-11-02 16:09:09 +01001024 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001025
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001026 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1027
1028 return NO_ERROR;
1029}
1030
1031status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1032 audio_io_handle_t *output,
1033 audio_session_t session,
1034 audio_stream_type_t *stream,
1035 uid_t uid,
1036 const audio_config_t *config,
1037 audio_output_flags_t *flags,
1038 audio_port_handle_t *selectedDeviceId,
1039 audio_port_handle_t *portId)
1040{
1041 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1042 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1043 return INVALID_OPERATION;
1044 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001045 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001046 audio_attributes_t resultAttr;
1047 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1048 config, flags, selectedDeviceId);
1049 if (status != NO_ERROR) {
1050 return status;
1051 }
1052
Eric Laurent8fc147b2018-07-22 19:13:55 -07001053 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1054 .format = config->format,
1055 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001056 *portId = AudioPort::getNextUniqueId();
1057
Eric Laurent8fc147b2018-07-22 19:13:55 -07001058 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001059 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001060 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001061 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -07001062 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001063 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001064 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001065
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001066 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +01001067 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001068
Eric Laurente83b55d2014-11-14 10:06:21 -08001069 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001070}
1071
François Gaffie11d30102018-11-02 16:09:09 +01001072audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1073 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001074 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001075 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001076 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001077 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001078{
Andy Hungc88b0642018-04-27 15:42:35 -07001079 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001080 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001081
Eric Laurente552edb2014-03-10 17:42:56 -07001082 // open a direct output if required by specified parameters
1083 //force direct flag if offload flag is set: offloading implies a direct output stream
1084 // and all common behaviors are driven by checking only the direct flag
1085 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001086 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1087 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001088 }
Nadav Bar766fb022018-01-07 12:18:03 +02001089 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1090 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001091 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001092 // only allow deep buffering for music stream type
1093 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001094 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001095 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001096 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001097 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1098 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001099 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001100 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001101 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001102 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001103 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001104 audio_is_linear_pcm(config->format) &&
1105 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001106 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001107 AUDIO_OUTPUT_FLAG_DIRECT);
1108 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001109 }
Eric Laurente552edb2014-03-10 17:42:56 -07001110
Nadav Bar766fb022018-01-07 12:18:03 +02001111
Eric Laurentb732cf52014-09-24 19:08:21 -07001112 sp<IOProfile> profile;
1113
1114 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001115 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001116 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001117 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1118 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001119 goto non_direct_output;
1120 }
1121
Andy Hung2ddee192015-12-18 17:34:44 -08001122 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1123 // This prevents creating an offloaded track and tearing it down immediately after start
1124 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001125 // FIXME: We should check the audio session here but we do not have it in this context.
1126 // This may prevent offloading in rare situations where effects are left active by apps
1127 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001128
Nadav Bar766fb022018-01-07 12:18:03 +02001129 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001130 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001131 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001132 config->sample_rate,
1133 config->format,
1134 config->channel_mask,
1135 (audio_output_flags_t)*flags,
1136 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001137 }
1138
Eric Laurent1c333e22014-05-20 10:48:17 -07001139 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001140 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1141 for (size_t i = 0; i < mOutputs.size(); i++) {
1142 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1143 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1144 // reuse direct output if currently open by the same client
1145 // and configured with same parameters
1146 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001147 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001148 (config->channel_mask == desc->mChannelMask) &&
1149 (session == desc->mDirectClientSession)) {
1150 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001151 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001152 mOutputs.keyAt(i), session);
1153 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155 }
1156 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001157
1158 if (!profile->canOpenNewIo()) {
1159 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
Eric Laurent861a6282015-05-18 15:40:16 -07001161
Eric Laurent3974e3b2017-12-07 17:58:43 -08001162 sp<SwAudioOutputDescriptor> outputDesc =
1163 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001164
François Gaffie11d30102018-11-02 16:09:09 +01001165 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001166
Dean Wheatley3023b382018-08-09 07:42:40 +10001167 // MSD patch may be using the only output stream that can service this request. Release
1168 // MSD patch to prioritize this request over any active output on MSD.
1169 AudioPatchCollection msdPatches = getMsdPatches();
1170 for (size_t i = 0; i < msdPatches.size(); i++) {
1171 const auto& patch = msdPatches[i];
1172 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1173 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1174 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001175 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001176 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1177 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1178 releaseAudioPatch(patch->mHandle, mUidCached);
1179 break;
1180 }
1181 }
1182 }
1183
François Gaffie11d30102018-11-02 16:09:09 +01001184 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001185
1186 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001187 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001188 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001189 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001190 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001191 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1192 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001193 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1194 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001195 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001196 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001197 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001198 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001199 if (audio_is_linear_pcm(config->format) &&
1200 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001201 goto non_direct_output;
1202 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001203 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001204 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001205 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001206 outputDesc->mDirectClientSession = session;
1207
Eric Laurente552edb2014-03-10 17:42:56 -07001208 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001209 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001210 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001211 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001212 return output;
1213 }
1214
Eric Laurentb732cf52014-09-24 19:08:21 -07001215non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001216
1217 // A request for HW A/V sync cannot fallback to a mixed output because time
1218 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001219 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001220 return AUDIO_IO_HANDLE_NONE;
1221 }
1222
Eric Laurente552edb2014-03-10 17:42:56 -07001223 // ignoring channel mask due to downmix capability in mixer
1224
1225 // open a non direct output
1226
1227 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001228 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001229 // get which output is suitable for the specified stream. The actual
1230 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001231 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001232
Eric Laurent8838a382014-09-08 16:44:28 -07001233 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001234 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001235 output = selectOutput(outputs, *flags, config->format,
1236 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001237 }
François Gaffie11d30102018-11-02 16:09:09 +01001238 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001239 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001240 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001241
Eric Laurente552edb2014-03-10 17:42:56 -07001242 return output;
1243}
1244
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001245sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001246 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1247 mAvailableInputDevices);
1248 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1249}
1250
1251DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1252 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1253 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001254}
1255
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001256const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1257 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001258 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1259 if (msdModule != 0) {
1260 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1261 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1262 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1263 const struct audio_port_config *source = &patch->mPatch.sources[j];
1264 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1265 source->ext.device.hw_module == msdModule->getHandle()) {
1266 msdPatches.addAudioPatch(patch->mHandle, patch);
1267 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 }
1269 }
1270 }
1271 return msdPatches;
1272}
1273
François Gaffie11d30102018-11-02 16:09:09 +01001274status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1276{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001277 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001278 if (msdModule == nullptr) {
1279 ALOGE("%s() unable to get MSD module", __func__);
1280 return NO_INIT;
1281 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001282 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001283 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001284 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001285 return NO_INIT;
1286 }
1287 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1288 if (inputProfiles.isEmpty()) {
1289 ALOGE("%s() no input profiles for MSD module", __func__);
1290 return NO_INIT;
1291 }
1292 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1293 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001294 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295 return NO_INIT;
1296 }
1297 AudioProfileVector msdProfiles;
1298 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1299 for (const auto &inProfile : inputProfiles) {
1300 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1301 msdProfiles.appendVector(inProfile->getAudioProfiles());
1302 }
1303 }
1304 AudioProfileVector deviceProfiles;
1305 for (const auto &outProfile : outputProfiles) {
1306 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1307 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1308 }
1309 }
1310 struct audio_config_base bestSinkConfig;
1311 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1312 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1313 &bestSinkConfig);
1314 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001315 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1316 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001317 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001318 }
1319 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1320 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1321 sinkConfig->format = bestSinkConfig.format;
1322 // For encoded streams force direct flag to prevent downstream mixing.
1323 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1324 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1325 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1326 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1327 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1328 sourceConfig->format = bestSinkConfig.format;
1329 // Copy input stream directly without any processing (e.g. resampling).
1330 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1331 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1332 if (hwAvSync) {
1333 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1334 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1335 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1336 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1337 }
1338 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1339 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1340 sinkConfig->config_mask |= config_mask;
1341 sourceConfig->config_mask |= config_mask;
1342 return NO_ERROR;
1343}
1344
François Gaffie11d30102018-11-02 16:09:09 +01001345PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346{
1347 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001348 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001349 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1350 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1351 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1352 // For now, we just forcefully try with HwAvSync first.
1353 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1354 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1355 getBestMsdAudioProfileFor(
1356 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1357 if (res == NO_ERROR) {
1358 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1359 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1360 }
1361 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1362 " supporting PCM format conversion.", __func__);
1363 return patchBuilder;
1364}
1365
François Gaffie11d30102018-11-02 16:09:09 +01001366status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1367 sp<DeviceDescriptor> device = outputDevice;
1368 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001369 // Use media strategy for unspecified output device. This should only
1370 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1371 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001372 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1373 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1374 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 }
François Gaffie11d30102018-11-02 16:09:09 +01001376 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1377 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001378 const struct audio_patch* patch = patchBuilder.patch();
1379 const AudioPatchCollection msdPatches = getMsdPatches();
1380 if (!msdPatches.isEmpty()) {
1381 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1382 "The current MSD prototype only supports one output patch");
1383 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1384 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1385 return NO_ERROR;
1386 }
1387 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1388 }
1389 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1390 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1391 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1392 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001393 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1394 device->toString().c_str(), patch->sources[0].format,
1395 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001396 return status;
1397}
1398
Eric Laurente0720872014-03-11 09:30:41 -07001399audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001400 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001401 audio_format_t format,
1402 audio_channel_mask_t channelMask,
1403 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001404{
1405 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001406 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001407 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001408 // 1: the output supporting haptic playback when requesting haptic playback
1409 // 2: the output with the highest number of requested policy flags
1410 // 3: the output with the bit depth the closest to the requested one
1411 // 4: the primary output
1412 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001413
1414 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001415 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001416 }
1417 if (outputs.size() == 1) {
1418 return outputs[0];
1419 }
1420
1421 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001422 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1423 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001424 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1425 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1426 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001427 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1428 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001429
Eric Laurente78b6762018-12-19 16:29:01 -08001430 // Flags which must be present on both the request and the selected output
1431 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1432 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1433
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001434 for (audio_io_handle_t output : outputs) {
1435 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001436 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001437 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1438 continue;
1439 }
jiabin40573322018-11-08 12:08:02 -08001440 // If haptic channel is specified, use the haptic output if present.
1441 // When using haptic output, same audio format and sample rate are required.
1442 if (hapticChannelCount > 0) {
1443 // If haptic channel is specified, use the first output that
1444 // support haptic playback.
1445 if (audio_channel_count_from_out_mask(
1446 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1447 && format == outputDesc->mFormat
1448 && samplingRate == outputDesc->mSamplingRate) {
1449 return output;
1450 }
1451 } else {
1452 // When haptic channel is not specified, skip haptic output.
1453 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1454 continue;
1455 }
1456 }
Eric Laurente78b6762018-12-19 16:29:01 -08001457 if ((kMandatedFlags & flags) !=
1458 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1459 continue;
1460 }
jiabin40573322018-11-08 12:08:02 -08001461
Eric Laurent8838a382014-09-08 16:44:28 -07001462 // if a valid format is specified, skip output if not compatible
1463 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001464 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001465 continue;
1466 }
Eric Laurente6930022016-02-11 10:20:40 -08001467 if (AudioPort::isBetterFormatMatch(
1468 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001469 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001470 bestFormat = outputDesc->mFormat;
1471 }
Eric Laurent8838a382014-09-08 16:44:28 -07001472 }
1473
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001474 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001475 if (commonFlags >= maxCommonFlags) {
1476 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001477 if (format != AUDIO_FORMAT_INVALID
1478 && AudioPort::isBetterFormatMatch(
1479 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001480 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001481 bestFormatForFlags = outputDesc->mFormat;
1482 }
1483 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001484 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001485 maxCommonFlags = commonFlags;
1486 bestFormatForFlags = outputDesc->mFormat;
1487 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001488 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001489 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001490 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001491 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001492 }
1493 }
1494 }
1495
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001496 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001497 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001498 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001499 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001500 return outputForFormat;
1501 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001502 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001503 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001504 }
1505
1506 return outputs[0];
1507}
1508
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001510{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001511 ALOGV("%s portId %d", __FUNCTION__, portId);
1512
1513 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1514 if (outputDesc == 0) {
1515 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001516 return BAD_VALUE;
1517 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001518 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001519
Eric Laurent8fc147b2018-07-22 19:13:55 -07001520 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001521 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001522
Eric Laurent733ce942017-12-07 12:18:25 -08001523 status_t status = outputDesc->start();
1524 if (status != NO_ERROR) {
1525 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001526 }
1527
Eric Laurent97ac8712018-07-27 18:59:02 -07001528 uint32_t delayMs;
1529 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001530
1531 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001532 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001533 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001534 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001535 if (delayMs != 0) {
1536 usleep(delayMs * 1000);
1537 }
1538
1539 return status;
1540}
1541
Eric Laurent97ac8712018-07-27 18:59:02 -07001542status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1543 const sp<TrackClientDescriptor>& client,
1544 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001545{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001546 // cannot start playback of STREAM_TTS if any other output is being used
1547 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001548
1549 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001550 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001551 if (stream == AUDIO_STREAM_TTS) {
1552 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001553 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001554 return INVALID_OPERATION;
1555 } else {
1556 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1557 }
1558 } else {
1559 // some playback other than beacon starts
1560 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1561 }
1562
Eric Laurent77305a62016-07-25 16:39:22 -07001563 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001564 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001565 bool force = !outputDesc->isActive() &&
1566 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001567
François Gaffie11d30102018-11-02 16:09:09 +01001568 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001569 AudioMix *policyMix = NULL;
1570 const char *address = NULL;
1571 if (outputDesc->mPolicyMix != NULL) {
1572 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001573 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001574 address = policyMix->mDeviceAddress.string();
1575 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001576 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001577 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001578 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001579 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001580 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1581 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001582 }
1583
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001584 // requiresMuteCheck is false when we can bypass mute strategy.
1585 // It covers a common case when there is no materially active audio
1586 // and muting would result in unnecessary delay and dropped audio.
1587 const uint32_t outputLatencyMs = outputDesc->latency();
1588 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1589
Eric Laurente552edb2014-03-10 17:42:56 -07001590 // increment usage count for this stream on the requested output:
1591 // NOTE that the usage count is the same for duplicated output and hardware output which is
1592 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001593 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001594
1595 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001596 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1597 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001598 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1599 }
1600 }
Eric Laurente552edb2014-03-10 17:42:56 -07001601
Eric Laurent36829f92017-04-07 19:04:42 -07001602 if (stream == AUDIO_STREAM_MUSIC) {
1603 selectOutputForMusicEffects();
1604 }
1605
François Gaffie11d30102018-11-02 16:09:09 +01001606 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001607 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001608 if (devices.isEmpty()) {
1609 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001610 }
Eric Laurent36829f92017-04-07 19:04:42 -07001611
Eric Laurente552edb2014-03-10 17:42:56 -07001612 routing_strategy strategy = getStrategy(stream);
1613 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001614 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1615 (beaconMuteLatency > 0);
1616 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001617 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001618 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001619 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001620 // An output has a shared device if
1621 // - managed by the same hw module
1622 // - supports the currently selected device
1623 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001624 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001625
Eric Laurent77305a62016-07-25 16:39:22 -07001626 // force a device change if any other output is:
1627 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001628 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001629 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001630 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001631 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001632 // change the device currently selected by the other output.
1633 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001634 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001635 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001636 force = true;
1637 }
1638 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001639 // a notification so that audio focus effect can propagate, or that a mute/unmute
1640 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001641 const uint32_t latencyMs = desc->latency();
1642 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1643
1644 if (shouldWait && isActive && (waitMs < latencyMs)) {
1645 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001646 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001647
1648 // Require mute check if another output is on a shared device
1649 // and currently active to have proper drain and avoid pops.
1650 // Note restoring AudioTracks onto this output needs to invoke
1651 // a volume ramp if there is no mute.
1652 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001653 }
1654 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001655
1656 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001657 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurente552edb2014-03-10 17:42:56 -07001659 // apply volume rules for current stream and device if necessary
1660 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001661 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001662 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001663 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001664
1665 // update the outputs if starting an output with a stream that can affect notification
1666 // routing
1667 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001668
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001669 // force reevaluating accessibility routing when ringtone or alarm starts
1670 if (strategy == STRATEGY_SONIFICATION) {
1671 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1672 }
Eric Laurentdc462862016-07-19 12:29:53 -07001673
1674 if (waitMs > muteWaitMs) {
1675 *delayMs = waitMs - muteWaitMs;
1676 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001677
1678 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1679 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1680 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1681 // change occurs after the MixerThread starts and causes a stream volume
1682 // glitch.
1683 //
1684 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001685 }
Eric Laurentdc462862016-07-19 12:29:53 -07001686
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001687 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1688 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1689 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1690 }
1691
Eric Laurent97ac8712018-07-27 18:59:02 -07001692 // Automatically enable the remote submix input when output is started on a re routing mix
1693 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001694 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001695 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1696 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1697 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1698 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001699 "remote-submix",
1700 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001701 }
1702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 return NO_ERROR;
1704}
1705
Eric Laurent8fc147b2018-07-22 19:13:55 -07001706status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001707{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001708 ALOGV("%s portId %d", __FUNCTION__, portId);
1709
1710 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1711 if (outputDesc == 0) {
1712 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001713 return BAD_VALUE;
1714 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001715 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Eric Laurent97ac8712018-07-27 18:59:02 -07001717 ALOGV("stopOutput() output %d, stream %d, session %d",
1718 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001719
Eric Laurent97ac8712018-07-27 18:59:02 -07001720 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001721
Eric Laurent733ce942017-12-07 12:18:25 -08001722 if (status == NO_ERROR ) {
1723 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001724 }
1725 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001726}
1727
Eric Laurent97ac8712018-07-27 18:59:02 -07001728status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1729 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001730{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001731 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001732 audio_stream_type_t stream = client->stream();
1733
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001734 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1735
Eric Laurent592dd7b2018-08-05 18:58:48 -07001736 if (outputDesc->streamActiveCount(stream) > 0) {
1737 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001738 // Automatically disable the remote submix input when output is stopped on a
1739 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001740 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001741 outputDesc->mPolicyMix != NULL &&
1742 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1743 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1744 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1745 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001746 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 }
1748 }
1749 bool forceDeviceUpdate = false;
1750 if (client->hasPreferredDevice(true)) {
1751 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1752 forceDeviceUpdate = true;
1753 }
1754
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001756 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001757
Eric Laurente552edb2014-03-10 17:42:56 -07001758 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001759 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001760 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001761 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001762 // delay the device switch by twice the latency because stopOutput() is executed when
1763 // the track stop() command is received and at that time the audio track buffer can
1764 // still contain data that needs to be drained. The latency only covers the audio HAL
1765 // and kernel buffers. Also the latency does not always include additional delay in the
1766 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001767 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001768
1769 // force restoring the device selection on other active outputs if it differs from the
1770 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001771 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001772 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001773 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001774 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001775 desc->isActive() &&
1776 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001777 (newDevices != desc->devices())) {
1778 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1779 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001780
François Gaffie11d30102018-11-02 16:09:09 +01001781 setOutputDevices(desc, newDevices2, force, delayMs);
1782
Eric Laurent57de36c2016-09-28 16:59:11 -07001783 // re-apply device specific volume if not done by setOutputDevice()
1784 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001785 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001786 }
Eric Laurente552edb2014-03-10 17:42:56 -07001787 }
1788 }
1789 // update the outputs if stopping one with a stream that can affect notification routing
1790 handleNotificationRoutingForStream(stream);
1791 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001792
1793 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1794 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1795 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1796 }
1797
Eric Laurent36829f92017-04-07 19:04:42 -07001798 if (stream == AUDIO_STREAM_MUSIC) {
1799 selectOutputForMusicEffects();
1800 }
Eric Laurente552edb2014-03-10 17:42:56 -07001801 return NO_ERROR;
1802 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001803 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001804 return INVALID_OPERATION;
1805 }
1806}
1807
Eric Laurent8fc147b2018-07-22 19:13:55 -07001808void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001809{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001810 ALOGV("%s portId %d", __FUNCTION__, portId);
1811
1812 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1813 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001814 // If an output descriptor is closed due to a device routing change,
1815 // then there are race conditions with releaseOutput from tracks
1816 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1817 // destroyed shortly thereafter.
1818 //
1819 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001820 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001821 return;
1822 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001823
1824 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001825
Eric Laurent8fc147b2018-07-22 19:13:55 -07001826 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1827 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001828 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001829 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001830 return;
1831 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001832 if (--outputDesc->mDirectOpenCount == 0) {
1833 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001834 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001835 }
1836 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001837 // stopOutput() needs to be successfully called before releaseOutput()
1838 // otherwise there may be inaccurate stream reference counts.
1839 // This is checked in outputDesc->removeClient below.
1840 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001841}
1842
Eric Laurentcaf7f482014-11-25 17:50:47 -08001843status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1844 audio_io_handle_t *input,
1845 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001846 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001847 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001848 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001849 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001850 input_type_t *inputType,
1851 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001852{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001853 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001854 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001855 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001856
Eric Laurentad2e7b92017-09-14 20:06:42 -07001857 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001858 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001859 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001860 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001861 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001862 sp<AudioInputDescriptor> inputDesc;
1863 sp<RecordClientDescriptor> clientDesc;
1864 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001865 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001866
1867 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1868 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1869 return INVALID_OPERATION;
1870 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001871
Francois Gaffie716e1432019-01-14 16:58:59 +01001872 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1873 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001874 }
1875
Paul McLean466dc8e2015-04-17 13:15:36 -06001876 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001877 sp<DeviceDescriptor> explicitRoutingDevice =
1878 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001879
Eric Laurentad2e7b92017-09-14 20:06:42 -07001880 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1881 // possible
1882 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1883 *input != AUDIO_IO_HANDLE_NONE) {
1884 ssize_t index = mInputs.indexOfKey(*input);
1885 if (index < 0) {
1886 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1887 status = BAD_VALUE;
1888 goto error;
1889 }
1890 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001891 RecordClientVector clients = inputDesc->getClientsForSession(session);
1892 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001893 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1894 status = BAD_VALUE;
1895 goto error;
1896 }
1897 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1898 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001899 // corresponds to a new client and is only permitted from the same UID.
1900 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001901 if (clients.size() > 1) {
1902 for (const auto& client : clients) {
1903 // The client map is ordered by key values (portId) and portIds are allocated
1904 // incrementaly. So the first client in this list is the one opened by audio flinger
1905 // when the mmap stream is created and should be ignored as it does not correspond
1906 // to an actual client
1907 if (client == *clients.cbegin()) {
1908 continue;
1909 }
1910 if (uid != client->uid() && !client->isSilenced()) {
1911 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1912 uid, client->portId(), client->uid());
1913 status = INVALID_OPERATION;
1914 goto error;
1915 }
Eric Laurent331679c2018-04-16 17:03:16 -07001916 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001917 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001918 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001919 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001920
Eric Laurent8f42ea12018-08-08 09:08:25 -07001921 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001922 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001923 }
1924
1925 *input = AUDIO_IO_HANDLE_NONE;
1926 *inputType = API_INPUT_INVALID;
1927
Francois Gaffie716e1432019-01-14 16:58:59 +01001928 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001929
Francois Gaffie716e1432019-01-14 16:58:59 +01001930 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1931 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1932 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001933 if (status != NO_ERROR) {
1934 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001935 }
1936 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001937 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001938 String8(attr->tags + strlen("addr=")),
1939 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001940 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001941 if (explicitRoutingDevice != nullptr) {
1942 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001943 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001944 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001945 }
François Gaffie11d30102018-11-02 16:09:09 +01001946 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001947 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001948 status = BAD_VALUE;
1949 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001950 }
François Gaffie11d30102018-11-02 16:09:09 +01001951 if (policyMix != nullptr) {
1952 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1953 // there is an external policy, but this input is attached to a mix of recorders,
1954 // meaning it receives audio injected into the framework, so the recorder doesn't
1955 // know about it and is therefore considered "legacy"
1956 *inputType = API_INPUT_LEGACY;
1957 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001958 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1959 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001960 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001961 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001962 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001963 } else {
1964 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001965 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001966
Eric Laurent599c7582015-12-07 18:05:55 -08001967 }
1968
Francois Gaffie716e1432019-01-14 16:58:59 +01001969 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001970 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001971 policyMix);
1972 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001973 status = INVALID_OPERATION;
1974 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001975 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001976
Eric Laurent8f42ea12018-08-08 09:08:25 -07001977exit:
1978
François Gaffie11d30102018-11-02 16:09:09 +01001979 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1980 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001981
Francois Gaffie716e1432019-01-14 16:58:59 +01001982 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001983 mSoundTriggerSessions.indexOfKey(session) > 0;
1984 *portId = AudioPort::getNextUniqueId();
1985
François Gaffie11d30102018-11-02 16:09:09 +01001986 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001987 requestedDeviceId, attributes.source, flags,
1988 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001989 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001990 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001991
1992 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1993 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001994
Eric Laurent599c7582015-12-07 18:05:55 -08001995 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001996
1997error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001998 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001999}
2000
2001
François Gaffie11d30102018-11-02 16:09:09 +01002002audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002003 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08002004 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08002005 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002006 audio_input_flags_t flags,
2007 AudioMix *policyMix)
2008{
2009 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2010 audio_source_t halInputSource = inputSource;
2011 bool isSoundTrigger = false;
2012
2013 if (inputSource == AUDIO_SOURCE_HOTWORD) {
2014 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2015 if (index >= 0) {
2016 input = mSoundTriggerSessions.valueFor(session);
2017 isSoundTrigger = true;
2018 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2019 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2020 } else {
2021 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002022 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002023 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002024 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002025 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002026 }
2027
Andy Hungf129b032015-04-07 13:45:50 -07002028 // find a compatible input profile (not necessarily identical in parameters)
2029 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002030 // sampling rate and flags may be updated by getInputProfile
2031 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2032 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002033 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002034 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002035 audio_input_flags_t profileFlags = flags;
2036 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002037 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002038 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002039 profileFlags);
2040 if (profile != 0) {
2041 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002042 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2043 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002044 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2045 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2046 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002047 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2048 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2049 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002050 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002051 }
Eric Laurente552edb2014-03-10 17:42:56 -07002052 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002053 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002054 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002055 if (samplingRate == 0) {
2056 samplingRate = profileSamplingRate;
2057 }
Eric Laurente552edb2014-03-10 17:42:56 -07002058
Eric Laurent322b4d22015-04-03 15:57:54 -07002059 if (profile->getModuleHandle() == 0) {
2060 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002061 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002062 }
2063
Eric Laurent3974e3b2017-12-07 17:58:43 -08002064 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002065 for (size_t i = 0; i < mInputs.size(); ) {
2066 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2067 if (desc->mProfile != profile) {
2068 continue;
2069 }
2070 // if sound trigger, reuse input if used by other sound trigger on same session
2071 // else
2072 // reuse input if active client app is not in IDLE state
2073 //
2074 RecordClientVector clients = desc->clientsList();
2075 bool doClose = false;
2076 for (const auto& client : clients) {
2077 if (isSoundTrigger != client->isSoundTrigger()) {
2078 continue;
2079 }
2080 if (client->isSoundTrigger()) {
2081 if (session == client->session()) {
2082 return desc->mIoHandle;
2083 }
2084 continue;
2085 }
2086 if (client->active() && client->appState() != APP_STATE_IDLE) {
2087 return desc->mIoHandle;
2088 }
2089 doClose = true;
2090 }
2091 if (doClose) {
2092 closeInput(desc->mIoHandle);
2093 } else {
2094 i++;
2095 }
2096 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002097 }
2098
Eric Laurentfe231122017-11-17 17:48:06 -08002099 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002100
Eric Laurentfe231122017-11-17 17:48:06 -08002101 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2102 lConfig.sample_rate = profileSamplingRate;
2103 lConfig.channel_mask = profileChannelMask;
2104 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002105
François Gaffie11d30102018-11-02 16:09:09 +01002106 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002107
2108 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002109 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002110 (profileSamplingRate != lConfig.sample_rate) ||
2111 !audio_formats_match(profileFormat, lConfig.format) ||
2112 (profileChannelMask != lConfig.channel_mask)) {
2113 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002114 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002115 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002116 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002117 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002118 }
Eric Laurent599c7582015-12-07 18:05:55 -08002119 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002120 }
2121
Eric Laurentc722f302014-12-10 11:21:49 -08002122 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002123
Eric Laurent599c7582015-12-07 18:05:55 -08002124 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002125 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002126
Eric Laurent599c7582015-12-07 18:05:55 -08002127 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002128}
2129
Eric Laurent4eb58f12018-12-07 16:41:02 -08002130status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002131{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002132 ALOGV("%s portId %d", __FUNCTION__, portId);
2133
2134 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2135 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002136 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002137 return BAD_VALUE;
2138 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002140 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002141 if (client->active()) {
2142 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2143 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002144 }
2145
Eric Laurent8f42ea12018-08-08 09:08:25 -07002146 audio_session_t session = client->session();
2147
Eric Laurent4eb58f12018-12-07 16:41:02 -08002148 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002149
Eric Laurent4eb58f12018-12-07 16:41:02 -08002150 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002151
Eric Laurent4eb58f12018-12-07 16:41:02 -08002152 status_t status = inputDesc->start();
2153 if (status != NO_ERROR) {
2154 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002155 }
Eric Laurente552edb2014-03-10 17:42:56 -07002156
Eric Laurent4eb58f12018-12-07 16:41:02 -08002157 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002158 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002159 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002160
Eric Laurent8f42ea12018-08-08 09:08:25 -07002161 // indicate active capture to sound trigger service if starting capture from a mic on
2162 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002163 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002164 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002165
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166 if (inputDesc->activeCount() == 1) {
2167 // if input maps to a dynamic policy with an activity listener, notify of state change
2168 if ((inputDesc->mPolicyMix != NULL)
2169 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2170 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2171 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002172 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002173
François Gaffie11d30102018-11-02 16:09:09 +01002174 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2175 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002176 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2177 SoundTrigger::setCaptureState(true);
2178 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002179
Eric Laurent8f42ea12018-08-08 09:08:25 -07002180 // automatically enable the remote submix output when input is started if not
2181 // used by a policy mix of type MIX_TYPE_RECORDERS
2182 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002183 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002184 String8 address = String8("");
2185 if (inputDesc->mPolicyMix == NULL) {
2186 address = String8("0");
2187 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2188 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002189 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190 if (address != "") {
2191 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2192 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002193 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002194 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002195 }
Eric Laurente552edb2014-03-10 17:42:56 -07002196 }
2197
Eric Laurent8f42ea12018-08-08 09:08:25 -07002198 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002199
Eric Laurente552edb2014-03-10 17:42:56 -07002200 return NO_ERROR;
2201}
2202
Eric Laurent8fc147b2018-07-22 19:13:55 -07002203status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002204{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002205 ALOGV("%s portId %d", __FUNCTION__, portId);
2206
2207 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2208 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002209 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002210 return BAD_VALUE;
2211 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002212 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002213 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002214 if (!client->active()) {
2215 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002216 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002217 }
2218
Eric Laurent8f42ea12018-08-08 09:08:25 -07002219 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002220
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 inputDesc->stop();
2222 if (inputDesc->isActive()) {
2223 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2224 } else {
2225 // if input maps to a dynamic policy with an activity listener, notify of state change
2226 if ((inputDesc->mPolicyMix != NULL)
2227 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2228 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2229 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002230 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002231
2232 // automatically disable the remote submix output when input is stopped if not
2233 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002234 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002235 String8 address = String8("");
2236 if (inputDesc->mPolicyMix == NULL) {
2237 address = String8("0");
2238 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2239 address = inputDesc->mPolicyMix->mDeviceAddress;
2240 }
2241 if (address != "") {
2242 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2243 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002244 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002245 }
2246 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002247 resetInputDevice(input);
2248
2249 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2250 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002251 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2252 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002253 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2254 SoundTrigger::setCaptureState(false);
2255 }
2256 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002257 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002258 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002259}
2260
Eric Laurent8fc147b2018-07-22 19:13:55 -07002261void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002262{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002263 ALOGV("%s portId %d", __FUNCTION__, portId);
2264
2265 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2266 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002267 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002268 return;
2269 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002270 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271 audio_io_handle_t input = inputDesc->mIoHandle;
2272
Eric Laurent8f42ea12018-08-08 09:08:25 -07002273 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002274
Andy Hung39efb7a2018-09-26 15:39:28 -07002275 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002276
Andy Hung39efb7a2018-09-26 15:39:28 -07002277 if (inputDesc->getClientCount() > 0) {
2278 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002279 return;
2280 }
2281
Eric Laurent05b90f82014-08-27 15:32:29 -07002282 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002283 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002284 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002285}
2286
Eric Laurent8f42ea12018-08-08 09:08:25 -07002287void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002288{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002289 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002290
2291 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002292 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002293 }
2294}
2295
Eric Laurent8f42ea12018-08-08 09:08:25 -07002296void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2297{
2298 stopInput(portId);
2299 releaseInput(portId);
2300}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002301
Eric Laurentd4692962014-05-05 18:13:44 -07002302void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002303 bool patchRemoved = false;
2304
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002305 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002306 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002307 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002308 if (patch_index >= 0) {
2309 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002310 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002311 mAudioPatches.removeItemsAt(patch_index);
2312 patchRemoved = true;
2313 }
Eric Laurentfe231122017-11-17 17:48:06 -08002314 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002315 }
2316 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002317 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002318 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002319
2320 if (patchRemoved) {
2321 mpClientInterface->onAudioPatchListUpdate();
2322 }
Eric Laurentd4692962014-05-05 18:13:44 -07002323}
2324
Eric Laurente0720872014-03-11 09:30:41 -07002325void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002326 int indexMin,
2327 int indexMax)
2328{
2329 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002330 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002331
2332 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002333 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2334 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002335 continue;
2336 }
2337 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002338 }
Eric Laurente552edb2014-03-10 17:42:56 -07002339}
2340
Eric Laurente0720872014-03-11 09:30:41 -07002341status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002342 int index,
2343 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002344{
2345
Nadav Bar7c605f62017-12-25 00:01:52 +02002346 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2347 // app that has MODIFY_PHONE_STATE permission.
2348 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2349 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002350 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002351 return BAD_VALUE;
2352 }
2353 if (!audio_is_output_device(device)) {
2354 return BAD_VALUE;
2355 }
2356
2357 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002358 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002359
Eric Laurent1fd372e2016-04-06 14:23:53 -07002360 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002361 stream, device, index);
2362
Eric Laurent28d09f02016-03-08 10:43:05 -08002363 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002364 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2365 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002366 continue;
2367 }
2368 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2369 }
Eric Laurente552edb2014-03-10 17:42:56 -07002370
Eric Laurent1fd372e2016-04-06 14:23:53 -07002371 // update volume on all outputs and streams matching the following:
2372 // - The requested stream (or a stream matching for volume control) is active on the output
2373 // - The device (or devices) selected by the strategy corresponding to this stream includes
2374 // the requested device
2375 // - For non default requested device, currently selected device on the output is either the
2376 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002377 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2378 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002379 status_t status = NO_ERROR;
2380 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002381 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002382 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002383 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002384 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002385 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002386 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002387 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002388 continue;
2389 }
Eric Laurent794fde22016-03-11 09:50:45 -08002390 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002391 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2392 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002393 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2394 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002395 continue;
2396 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002397 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002398 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002399 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002400 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002401 } else {
2402 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002403 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002404 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002405 // rescale index before applying to curStream as ranges may be different for
2406 // stream and curStream
2407 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002408 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002409 //FIXME: workaround for truncated touch sounds
2410 // delayed volume change for system stream to be removed when the problem is
2411 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002412 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002413 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002414 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002415 if (volStatus != NO_ERROR) {
2416 status = volStatus;
2417 }
2418 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002419 }
Eric Laurente552edb2014-03-10 17:42:56 -07002420 }
2421 return status;
2422}
2423
Eric Laurente0720872014-03-11 09:30:41 -07002424status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002425 int *index,
2426 audio_devices_t device)
2427{
2428 if (index == NULL) {
2429 return BAD_VALUE;
2430 }
2431 if (!audio_is_output_device(device)) {
2432 return BAD_VALUE;
2433 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002434 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002435 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002436 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002437 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2438 }
François Gaffiedfd74092015-03-19 12:10:59 +01002439 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002440
François Gaffied1ab2bd2015-12-02 18:20:06 +01002441 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002442 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2443 return NO_ERROR;
2444}
2445
Eric Laurent36829f92017-04-07 19:04:42 -07002446audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002447{
2448 // select one output among several suitable for global effects.
2449 // The priority is as follows:
2450 // 1: An offloaded output. If the effect ends up not being offloadable,
2451 // AudioFlinger will invalidate the track and the offloaded output
2452 // will be closed causing the effect to be moved to a PCM output.
2453 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002454 // 3: The primary output
2455 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002456
Eric Laurent3b73df72014-03-11 09:06:29 -07002457 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002458 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2459 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002460
Eric Laurent36829f92017-04-07 19:04:42 -07002461 if (outputs.size() == 0) {
2462 return AUDIO_IO_HANDLE_NONE;
2463 }
Eric Laurente552edb2014-03-10 17:42:56 -07002464
Eric Laurent36829f92017-04-07 19:04:42 -07002465 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2466 bool activeOnly = true;
2467
2468 while (output == AUDIO_IO_HANDLE_NONE) {
2469 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2470 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2471 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2472
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002473 for (audio_io_handle_t output : outputs) {
2474 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002475 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2476 continue;
2477 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002478 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2479 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002480 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002481 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002482 }
2483 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002484 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002485 }
2486 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002487 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002488 }
2489 }
2490 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2491 output = outputOffloaded;
2492 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2493 output = outputDeepBuffer;
2494 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2495 output = outputPrimary;
2496 } else {
2497 output = outputs[0];
2498 }
2499 activeOnly = false;
2500 }
2501
2502 if (output != mMusicEffectOutput) {
2503 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2504 mMusicEffectOutput = output;
2505 }
2506
2507 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002508 return output;
2509}
2510
Eric Laurent36829f92017-04-07 19:04:42 -07002511audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2512{
2513 return selectOutputForMusicEffects();
2514}
2515
Eric Laurente0720872014-03-11 09:30:41 -07002516status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002517 audio_io_handle_t io,
2518 uint32_t strategy,
2519 int session,
2520 int id)
2521{
2522 ssize_t index = mOutputs.indexOfKey(io);
2523 if (index < 0) {
2524 index = mInputs.indexOfKey(io);
2525 if (index < 0) {
2526 ALOGW("registerEffect() unknown io %d", io);
2527 return INVALID_OPERATION;
2528 }
2529 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002530 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002531}
2532
Eric Laurentc241b0d2018-11-28 09:08:49 -08002533status_t AudioPolicyManager::unregisterEffect(int id)
2534{
2535 if (mEffects.getEffect(id) == nullptr) {
2536 return INVALID_OPERATION;
2537 }
2538
2539 if (mEffects.isEffectEnabled(id)) {
2540 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2541 setEffectEnabled(id, false);
2542 }
2543 return mEffects.unregisterEffect(id);
2544}
2545
2546status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2547{
2548 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2549 if (effect == nullptr) {
2550 return INVALID_OPERATION;
2551 }
2552
2553 status_t status = mEffects.setEffectEnabled(id, enabled);
2554 if (status == NO_ERROR) {
2555 mInputs.trackEffectEnabled(effect, enabled);
2556 }
2557 return status;
2558}
2559
Eric Laurentc75307b2015-03-17 15:29:32 -07002560bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2561{
Eric Laurent28d09f02016-03-08 10:43:05 -08002562 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002563 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2564 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002565 continue;
2566 }
2567 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2568 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002569 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002570}
2571
2572bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2573{
2574 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2575}
2576
Eric Laurente0720872014-03-11 09:30:41 -07002577bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
2579 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002580 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002581 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002582 return true;
2583 }
2584 }
2585 return false;
2586}
2587
Eric Laurent275e8e92014-11-30 15:14:47 -08002588// Register a list of custom mixes with their attributes and format.
2589// When a mix is registered, corresponding input and output profiles are
2590// added to the remote submix hw module. The profile contains only the
2591// parameters (sampling rate, format...) specified by the mix.
2592// The corresponding input remote submix device is also connected.
2593//
2594// When a remote submix device is connected, the address is checked to select the
2595// appropriate profile and the corresponding input or output stream is opened.
2596//
2597// When capture starts, getInputForAttr() will:
2598// - 1 look for a mix matching the address passed in attribtutes tags if any
2599// - 2 if none found, getDeviceForInputSource() will:
2600// - 2.1 look for a mix matching the attributes source
2601// - 2.2 if none found, default to device selection by policy rules
2602// At this time, the corresponding output remote submix device is also connected
2603// and active playback use cases can be transferred to this mix if needed when reconnecting
2604// after AudioTracks are invalidated
2605//
2606// When playback starts, getOutputForAttr() will:
2607// - 1 look for a mix matching the address passed in attribtutes tags if any
2608// - 2 if none found, look for a mix matching the attributes usage
2609// - 3 if none found, default to device and output selection by policy rules.
2610
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002611status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002612{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002613 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2614 status_t res = NO_ERROR;
2615
2616 sp<HwModule> rSubmixModule;
2617 // examine each mix's route type
2618 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002619 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002620 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002621 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002622 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002623 break;
2624 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002627 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002628 rSubmixModule = mHwModules.getModuleFromName(
2629 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2630 if (rSubmixModule == 0) {
2631 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2632 i);
2633 res = INVALID_OPERATION;
2634 break;
2635 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002637
Eric Laurent97ac8712018-07-27 18:59:02 -07002638 String8 address = mix.mDeviceAddress;
2639 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2640 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2641 } else {
2642 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2643 }
François Gaffie036e1e92015-03-19 10:16:24 +01002644
Eric Laurent97ac8712018-07-27 18:59:02 -07002645 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002646 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 res = INVALID_OPERATION;
2648 break;
2649 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002650 audio_config_t outputConfig = mix.mFormat;
2651 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002652 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2653 // stereo and let audio flinger do the channel conversion if needed.
2654 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2655 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2656 rSubmixModule->addOutputProfile(address, &outputConfig,
2657 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2658 rSubmixModule->addInputProfile(address, &inputConfig,
2659 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002660
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002662 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2663 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002664 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002665 } else {
2666 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2667 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002668 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002670 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2671 String8 address = mix.mDeviceAddress;
2672 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002673 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2674 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002675
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002676 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002677 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2678 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2679 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2680 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2681 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2682 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002683 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2684 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002685 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002686 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002687 } else {
2688 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002689 }
2690 break;
2691 }
2692 }
2693
2694 if (res != NO_ERROR) {
2695 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002696 i, device, address.string());
2697 res = INVALID_OPERATION;
2698 break;
2699 } else if (!foundOutput) {
2700 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2701 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002702 res = INVALID_OPERATION;
2703 break;
2704 }
Eric Laurentc722f302014-12-10 11:21:49 -08002705 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002706 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002707 if (res != NO_ERROR) {
2708 unregisterPolicyMixes(mixes);
2709 }
2710 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002711}
2712
2713status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2714{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002715 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002716 status_t res = NO_ERROR;
2717 sp<HwModule> rSubmixModule;
2718 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002719 for (const auto& mix : mixes) {
2720 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002721
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002722 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002723 rSubmixModule = mHwModules.getModuleFromName(
2724 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2725 if (rSubmixModule == 0) {
2726 res = INVALID_OPERATION;
2727 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002728 }
2729 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002730
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002731 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002732
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002733 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2734 res = INVALID_OPERATION;
2735 continue;
2736 }
2737
2738 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2739 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2740 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2741 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002742 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002743 }
2744 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2745 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2746 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2747 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002748 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002749 }
2750 rSubmixModule->removeOutputProfile(address);
2751 rSubmixModule->removeInputProfile(address);
2752
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002753 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2754 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002755 res = INVALID_OPERATION;
2756 continue;
2757 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002758 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002759 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002760 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002761}
2762
Mikhail Naganov100f0122018-11-29 11:22:16 -08002763void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2764{
2765 size_t i = 0;
2766 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2767 for (const auto& fmt : mManualSurroundFormats) {
2768 if (i++ != 0) dst->append(", ");
2769 std::string sfmt;
2770 FormatConverter::toString(fmt, sfmt);
2771 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2772 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2773 }
2774}
2775
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002776status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2777 const Vector<AudioDeviceTypeAddr>& devices) {
2778 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2779 // uid/device affinity is only for output devices
2780 for (size_t i = 0; i < devices.size(); i++) {
2781 if (!audio_is_output_device(devices[i].mType)) {
2782 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2783 devices[i].mType);
2784 return BAD_VALUE;
2785 }
2786 }
2787 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2788 if (res == NO_ERROR) {
2789 // reevaluate outputs for all given devices
2790 for (size_t i = 0; i < devices.size(); i++) {
2791 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002792 devices[i].mType, devices[i].mAddress, String8(),
2793 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002794 SortedVector<audio_io_handle_t> outputs;
2795 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002796 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002797 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2798 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2799 return INVALID_OPERATION;
2800 }
2801 }
2802 }
2803 return res;
2804}
2805
2806status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2807 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2808 Vector<AudioDeviceTypeAddr> devices;
2809 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2810 if (res == NO_ERROR) {
2811 // reevaluate outputs for all found devices
2812 for (size_t i = 0; i < devices.size(); i++) {
2813 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002814 devices[i].mType, devices[i].mAddress, String8(),
2815 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002816 SortedVector<audio_io_handle_t> outputs;
2817 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002818 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002819 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2820 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2821 return INVALID_OPERATION;
2822 }
2823 }
2824 }
2825
2826 return res;
2827}
2828
Andy Hungc29d82b2018-10-05 12:23:17 -07002829void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002830{
Andy Hungc29d82b2018-10-05 12:23:17 -07002831 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2832 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002833 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002834 std::string stateLiteral;
2835 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002836 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002837 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2838 "communications", "media", "record", "dock", "system",
2839 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2840 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2841 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002842 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2843 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2844 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2845 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2846 dst->append(" (MANUAL: ");
2847 dumpManualSurroundFormats(dst);
2848 dst->append(")");
2849 }
2850 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002851 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002852 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2853 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2854 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2855 mAvailableOutputDevices.dump(dst, String8("Available output"));
2856 mAvailableInputDevices.dump(dst, String8("Available input"));
2857 mHwModulesAll.dump(dst);
2858 mOutputs.dump(dst);
2859 mInputs.dump(dst);
2860 mVolumeCurves->dump(dst);
2861 mEffects.dump(dst);
2862 mAudioPatches.dump(dst);
2863 mPolicyMixes.dump(dst);
2864 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002865}
2866
2867status_t AudioPolicyManager::dump(int fd)
2868{
2869 String8 result;
2870 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002871 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002872 return NO_ERROR;
2873}
2874
2875// This function checks for the parameters which can be offloaded.
2876// This can be enhanced depending on the capability of the DSP and policy
2877// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002878bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002879{
2880 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002881 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002882 offloadInfo.sample_rate, offloadInfo.channel_mask,
2883 offloadInfo.format,
2884 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2885 offloadInfo.has_video);
2886
Andy Hung2ddee192015-12-18 17:34:44 -08002887 if (mMasterMono) {
2888 return false; // no offloading if mono is set.
2889 }
2890
Eric Laurente552edb2014-03-10 17:42:56 -07002891 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002892 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2893 ALOGV("offload disabled by audio.offload.disable");
2894 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002895 }
2896
2897 // Check if stream type is music, then only allow offload as of now.
2898 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2899 {
2900 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2901 return false;
2902 }
2903
2904 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002905 const bool allowOffloadWithVideo =
2906 property_get_bool("audio.offload.video", false /* default_value */);
2907 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002908 ALOGV("isOffloadSupported: has_video == true, returning false");
2909 return false;
2910 }
2911
2912 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002913 const int min_duration_secs = property_get_int32(
2914 "audio.offload.min.duration.secs", -1 /* default_value */);
2915 if (min_duration_secs >= 0) {
2916 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2917 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2918 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002919 return false;
2920 }
2921 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2922 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2923 return false;
2924 }
2925
2926 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2927 // creating an offloaded track and tearing it down immediately after start when audioflinger
2928 // detects there is an active non offloadable effect.
2929 // FIXME: We should check the audio session here but we do not have it in this context.
2930 // This may prevent offloading in rare situations where effects are left active by apps
2931 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002932 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002933 return false;
2934 }
2935
2936 // See if there is a profile to support this.
2937 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002938 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002939 offloadInfo.sample_rate,
2940 offloadInfo.format,
2941 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002942 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2943 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002944 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2945 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002946}
2947
Michael Chana94fbb22018-04-24 14:31:19 +10002948bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2949 const audio_attributes_t& attributes) {
2950 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2951 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002952 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002953 config.sample_rate,
2954 config.format,
2955 config.channel_mask,
2956 output_flags,
2957 true /* directOnly */);
2958 ALOGV("%s() profile %sfound with name: %s, "
2959 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2960 __FUNCTION__, profile != 0 ? "" : "NOT ",
2961 (profile != 0 ? profile->getTagName().string() : "null"),
2962 config.sample_rate, config.format, config.channel_mask, output_flags);
2963 return (profile != 0);
2964}
2965
Eric Laurent6a94d692014-05-20 11:18:06 -07002966status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2967 audio_port_type_t type,
2968 unsigned int *num_ports,
2969 struct audio_port *ports,
2970 unsigned int *generation)
2971{
2972 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2973 generation == NULL) {
2974 return BAD_VALUE;
2975 }
2976 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2977 if (ports == NULL) {
2978 *num_ports = 0;
2979 }
2980
2981 size_t portsWritten = 0;
2982 size_t portsMax = *num_ports;
2983 *num_ports = 0;
2984 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002985 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2986 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002988 for (const auto& dev : mAvailableOutputDevices) {
2989 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002990 continue;
2991 }
2992 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002993 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002994 }
2995 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 }
2998 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002999 for (const auto& dev : mAvailableInputDevices) {
3000 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003001 continue;
3002 }
3003 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003004 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003005 }
3006 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 }
3009 }
3010 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3011 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3012 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3013 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3014 }
3015 *num_ports += mInputs.size();
3016 }
3017 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003018 size_t numOutputs = 0;
3019 for (size_t i = 0; i < mOutputs.size(); i++) {
3020 if (!mOutputs[i]->isDuplicated()) {
3021 numOutputs++;
3022 if (portsWritten < portsMax) {
3023 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3024 }
3025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 }
Eric Laurent84c70242014-06-23 08:46:27 -07003027 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003028 }
3029 }
3030 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003031 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003032 return NO_ERROR;
3033}
3034
Eric Laurent99fcae42018-05-17 16:59:18 -07003035status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003036{
Eric Laurent99fcae42018-05-17 16:59:18 -07003037 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3038 return BAD_VALUE;
3039 }
3040 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3041 if (dev != 0) {
3042 dev->toAudioPort(port);
3043 return NO_ERROR;
3044 }
3045 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3046 if (dev != 0) {
3047 dev->toAudioPort(port);
3048 return NO_ERROR;
3049 }
3050 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3051 if (out != 0) {
3052 out->toAudioPort(port);
3053 return NO_ERROR;
3054 }
3055 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3056 if (in != 0) {
3057 in->toAudioPort(port);
3058 return NO_ERROR;
3059 }
3060 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003061}
3062
Eric Laurent6a94d692014-05-20 11:18:06 -07003063status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3064 audio_patch_handle_t *handle,
3065 uid_t uid)
3066{
3067 ALOGV("createAudioPatch()");
3068
3069 if (handle == NULL || patch == NULL) {
3070 return BAD_VALUE;
3071 }
3072 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3073
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003074 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003075 return BAD_VALUE;
3076 }
3077 // only one source per audio patch supported for now
3078 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003079 return INVALID_OPERATION;
3080 }
Eric Laurent874c42872014-08-08 15:13:39 -07003081
3082 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003083 return INVALID_OPERATION;
3084 }
Eric Laurent874c42872014-08-08 15:13:39 -07003085 for (size_t i = 0; i < patch->num_sinks; i++) {
3086 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3087 return INVALID_OPERATION;
3088 }
3089 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003090
3091 sp<AudioPatch> patchDesc;
3092 ssize_t index = mAudioPatches.indexOfKey(*handle);
3093
Eric Laurent6a94d692014-05-20 11:18:06 -07003094 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3095 patch->sources[0].role,
3096 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003097#if LOG_NDEBUG == 0
3098 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003099 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003100 patch->sinks[i].role,
3101 patch->sinks[i].type);
3102 }
3103#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003104
3105 if (index >= 0) {
3106 patchDesc = mAudioPatches.valueAt(index);
3107 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3108 mUidCached, patchDesc->mUid, uid);
3109 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3110 return INVALID_OPERATION;
3111 }
3112 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003113 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 }
3115
3116 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003118 if (outputDesc == NULL) {
3119 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3120 return BAD_VALUE;
3121 }
Eric Laurent84c70242014-06-23 08:46:27 -07003122 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3123 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 if (patchDesc != 0) {
3125 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3126 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3127 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3128 return BAD_VALUE;
3129 }
3130 }
Eric Laurent874c42872014-08-08 15:13:39 -07003131 DeviceVector devices;
3132 for (size_t i = 0; i < patch->num_sinks; i++) {
3133 // Only support mix to devices connection
3134 // TODO add support for mix to mix connection
3135 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3136 ALOGV("createAudioPatch() source mix but sink is not a device");
3137 return INVALID_OPERATION;
3138 }
3139 sp<DeviceDescriptor> devDesc =
3140 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3141 if (devDesc == 0) {
3142 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3143 return BAD_VALUE;
3144 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003145
François Gaffie11d30102018-11-02 16:09:09 +01003146 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003147 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003148 NULL, // updatedSamplingRate
3149 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003150 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003151 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003152 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003153 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003154 ALOGV("createAudioPatch() profile not supported for device %08x",
3155 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003156 return INVALID_OPERATION;
3157 }
3158 devices.add(devDesc);
3159 }
3160 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 return INVALID_OPERATION;
3162 }
Eric Laurent874c42872014-08-08 15:13:39 -07003163
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 // TODO: reconfigure output format and channels here
3165 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003166 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003167 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003168 index = mAudioPatches.indexOfKey(*handle);
3169 if (index >= 0) {
3170 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3171 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3172 }
3173 patchDesc = mAudioPatches.valueAt(index);
3174 patchDesc->mUid = uid;
3175 ALOGV("createAudioPatch() success");
3176 } else {
3177 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3178 return INVALID_OPERATION;
3179 }
3180 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3181 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3182 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003183 // only one sink supported when connecting an input device to a mix
3184 if (patch->num_sinks > 1) {
3185 return INVALID_OPERATION;
3186 }
François Gaffie53615e22015-03-19 09:24:12 +01003187 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 if (inputDesc == NULL) {
3189 return BAD_VALUE;
3190 }
3191 if (patchDesc != 0) {
3192 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3193 return BAD_VALUE;
3194 }
3195 }
François Gaffie11d30102018-11-02 16:09:09 +01003196 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003198 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003199 return BAD_VALUE;
3200 }
3201
François Gaffie11d30102018-11-02 16:09:09 +01003202 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003203 patch->sinks[0].sample_rate,
3204 NULL, /*updatedSampleRate*/
3205 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003206 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003207 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003208 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003209 // FIXME for the parameter type,
3210 // and the NONE
3211 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003212 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003213 return INVALID_OPERATION;
3214 }
3215 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003216 ALOGV("%s() setting device %s on output %d", __func__,
3217 device->toString().c_str(), inputDesc->mIoHandle);
3218 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003219 index = mAudioPatches.indexOfKey(*handle);
3220 if (index >= 0) {
3221 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3222 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3223 }
3224 patchDesc = mAudioPatches.valueAt(index);
3225 patchDesc->mUid = uid;
3226 ALOGV("createAudioPatch() success");
3227 } else {
3228 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3229 return INVALID_OPERATION;
3230 }
3231 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3232 // device to device connection
3233 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003234 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003235 return BAD_VALUE;
3236 }
3237 }
François Gaffie11d30102018-11-02 16:09:09 +01003238 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003240 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003241 return BAD_VALUE;
3242 }
Eric Laurent874c42872014-08-08 15:13:39 -07003243
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 //update source and sink with our own data as the data passed in the patch may
3245 // be incomplete.
3246 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003247 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003248
Eric Laurent874c42872014-08-08 15:13:39 -07003249 for (size_t i = 0; i < patch->num_sinks; i++) {
3250 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3251 ALOGV("createAudioPatch() source device but one sink is not a device");
3252 return INVALID_OPERATION;
3253 }
3254
François Gaffie11d30102018-11-02 16:09:09 +01003255 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003256 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003257 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003258 return BAD_VALUE;
3259 }
François Gaffie11d30102018-11-02 16:09:09 +01003260 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003261
Eric Laurent3bcf8592015-04-03 12:13:24 -07003262 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003263 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003264 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003265 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003266 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3267 (srcDevice->getModuleVersionMajor() < 3) ||
3268 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003269 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003270 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003271 return INVALID_OPERATION;
3272 }
Eric Laurent874c42872014-08-08 15:13:39 -07003273 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003274 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003275 // if the sink device is reachable via an opened output stream, request to go via
3276 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003277 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003278 if (output != AUDIO_IO_HANDLE_NONE) {
3279 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3280 if (outputDesc->isDuplicated()) {
3281 return INVALID_OPERATION;
3282 }
3283 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003284 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003285 newPatch.num_sources = 2;
3286 }
Eric Laurent83b88082014-06-20 18:31:16 -07003287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003288 }
3289 // TODO: check from routing capabilities in config file and other conflicting patches
3290
Mikhail Naganovdc769682018-05-04 15:34:08 -07003291 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3292 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003293 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3294 status);
3295 return INVALID_OPERATION;
3296 }
3297 } else {
3298 return BAD_VALUE;
3299 }
3300 } else {
3301 return BAD_VALUE;
3302 }
3303 return NO_ERROR;
3304}
3305
3306status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3307 uid_t uid)
3308{
3309 ALOGV("releaseAudioPatch() patch %d", handle);
3310
3311 ssize_t index = mAudioPatches.indexOfKey(handle);
3312
3313 if (index < 0) {
3314 return BAD_VALUE;
3315 }
3316 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3317 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3318 mUidCached, patchDesc->mUid, uid);
3319 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3320 return INVALID_OPERATION;
3321 }
3322
3323 struct audio_patch *patch = &patchDesc->mPatch;
3324 patchDesc->mUid = mUidCached;
3325 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003326 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003327 if (outputDesc == NULL) {
3328 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3329 return BAD_VALUE;
3330 }
3331
François Gaffie11d30102018-11-02 16:09:09 +01003332 setOutputDevices(outputDesc,
3333 getNewOutputDevices(outputDesc, true /*fromCache*/),
3334 true,
3335 0,
3336 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3338 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003339 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003340 if (inputDesc == NULL) {
3341 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3342 return BAD_VALUE;
3343 }
3344 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003345 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003346 true,
3347 NULL);
3348 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003349 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3350 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3351 status, patchDesc->mAfPatchHandle);
3352 removeAudioPatch(patchDesc->mHandle);
3353 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003354 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003355 } else {
3356 return BAD_VALUE;
3357 }
3358 } else {
3359 return BAD_VALUE;
3360 }
3361 return NO_ERROR;
3362}
3363
3364status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3365 struct audio_patch *patches,
3366 unsigned int *generation)
3367{
François Gaffie53615e22015-03-19 09:24:12 +01003368 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003369 return BAD_VALUE;
3370 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003371 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003372 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003373}
3374
Eric Laurente1715a42014-05-20 11:30:42 -07003375status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003376{
Eric Laurente1715a42014-05-20 11:30:42 -07003377 ALOGV("setAudioPortConfig()");
3378
3379 if (config == NULL) {
3380 return BAD_VALUE;
3381 }
3382 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3383 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003384 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3385 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003386 }
3387
Eric Laurenta121f902014-06-03 13:32:54 -07003388 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003389 if (config->type == AUDIO_PORT_TYPE_MIX) {
3390 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003392 if (outputDesc == NULL) {
3393 return BAD_VALUE;
3394 }
Eric Laurent84c70242014-06-23 08:46:27 -07003395 ALOG_ASSERT(!outputDesc->isDuplicated(),
3396 "setAudioPortConfig() called on duplicated output %d",
3397 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003398 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003399 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003400 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003401 if (inputDesc == NULL) {
3402 return BAD_VALUE;
3403 }
Eric Laurenta121f902014-06-03 13:32:54 -07003404 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003405 } else {
3406 return BAD_VALUE;
3407 }
3408 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3409 sp<DeviceDescriptor> deviceDesc;
3410 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3411 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3412 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3413 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3414 } else {
3415 return BAD_VALUE;
3416 }
3417 if (deviceDesc == NULL) {
3418 return BAD_VALUE;
3419 }
Eric Laurenta121f902014-06-03 13:32:54 -07003420 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003421 } else {
3422 return BAD_VALUE;
3423 }
3424
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003425 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003426 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3427 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003428 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003429 audioPortConfig->toAudioPortConfig(&newConfig, config);
3430 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003431 }
Eric Laurenta121f902014-06-03 13:32:54 -07003432 if (status != NO_ERROR) {
3433 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003434 }
Eric Laurente1715a42014-05-20 11:30:42 -07003435
3436 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003437}
3438
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003439void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3440{
Eric Laurentd60560a2015-04-10 11:31:20 -07003441 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003442 clearAudioPatches(uid);
3443 clearSessionRoutes(uid);
3444}
3445
Eric Laurent6a94d692014-05-20 11:18:06 -07003446void AudioPolicyManager::clearAudioPatches(uid_t uid)
3447{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003448 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003449 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3450 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003451 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003452 }
3453 }
3454}
3455
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003456void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3457 audio_io_handle_t ouptutToSkip)
3458{
François Gaffie11d30102018-11-02 16:09:09 +01003459 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3460 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003461 for (size_t j = 0; j < mOutputs.size(); j++) {
3462 if (mOutputs.keyAt(j) == ouptutToSkip) {
3463 continue;
3464 }
3465 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3466 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3467 continue;
3468 }
3469 // If the default device for this strategy is on another output mix,
3470 // invalidate all tracks in this strategy to force re connection.
3471 // Otherwise select new device on the output mix.
3472 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003473 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003474 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3475 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3476 }
3477 }
3478 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003479 setOutputDevices(
3480 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003481 }
3482 }
3483}
3484
3485void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3486{
3487 // remove output routes associated with this uid
3488 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003489 for (size_t i = 0; i < mOutputs.size(); i++) {
3490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003491 for (const auto& client : outputDesc->getClientIterable()) {
3492 if (client->hasPreferredDevice() && client->uid() == uid) {
3493 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3494 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003495 }
3496 }
3497 }
3498 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003499 for (const auto& strategy : affectedStrategies) {
3500 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003501 }
3502
3503 // remove input routes associated with this uid
3504 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003505 for (size_t i = 0; i < mInputs.size(); i++) {
3506 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003507 for (const auto& client : inputDesc->getClientIterable()) {
3508 if (client->hasPreferredDevice() && client->uid() == uid) {
3509 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3510 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003511 }
3512 }
3513 }
3514 // reroute inputs if necessary
3515 SortedVector<audio_io_handle_t> inputsToClose;
3516 for (size_t i = 0; i < mInputs.size(); i++) {
3517 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003518 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003519 inputsToClose.add(inputDesc->mIoHandle);
3520 }
3521 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003522 for (const auto& input : inputsToClose) {
3523 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003524 }
3525}
3526
Eric Laurentd60560a2015-04-10 11:31:20 -07003527void AudioPolicyManager::clearAudioSources(uid_t uid)
3528{
3529 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003530 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3531 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003532 stopAudioSource(mAudioSources.keyAt(i));
3533 }
3534 }
3535}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003536
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003537status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3538 audio_io_handle_t *ioHandle,
3539 audio_devices_t *device)
3540{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003541 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3542 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003543 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3544 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003545
François Gaffiedf372692015-03-19 10:43:27 +01003546 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003547}
3548
Eric Laurentd60560a2015-04-10 11:31:20 -07003549status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003550 const audio_attributes_t *attributes,
3551 audio_port_handle_t *portId,
3552 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003553{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003554 ALOGV("%s", __FUNCTION__);
3555 *portId = AUDIO_PORT_HANDLE_NONE;
3556
3557 if (source == NULL || attributes == NULL || portId == NULL) {
3558 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3559 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003560 return BAD_VALUE;
3561 }
3562
Eric Laurentd60560a2015-04-10 11:31:20 -07003563 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3564 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003565 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3566 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003567 return INVALID_OPERATION;
3568 }
3569
François Gaffie11d30102018-11-02 16:09:09 +01003570 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003571 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003572 String8(source->ext.device.address),
3573 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003574 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003575 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003576 return BAD_VALUE;
3577 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003578
3579 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003580
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003581 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003582 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003583
3584 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003585 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003586 streamTypefromAttributesInt(attributes),
3587 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003588
3589 status_t status = connectAudioSource(sourceDesc);
3590 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003591 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003592 }
3593 return status;
3594}
3595
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003596status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003597{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003598 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003599
3600 // make sure we only have one patch per source.
3601 disconnectAudioSource(sourceDesc);
3602
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003603 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003604 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003605 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003606 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003607
François Gaffie11d30102018-11-02 16:09:09 +01003608 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3609 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3610 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3611 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3612 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003613
3614 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003615
François Gaffie11d30102018-11-02 16:09:09 +01003616 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3617 srcDevice->getModuleVersionMajor() >= 3 &&
3618 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3619 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003620 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003621 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003622 // create patch between src device and output device
3623 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003624 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003625 audio_attributes_t resultAttr;
3626 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3627 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3628 config.sample_rate = sourceDesc->config().sample_rate;
3629 config.channel_mask = sourceDesc->config().channel_mask;
3630 config.format = sourceDesc->config().format;
3631 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3632 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3633 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3634 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003635 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003636 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003637 return INVALID_OPERATION;
3638 }
3639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3640 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003641 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003642 return INVALID_OPERATION;
3643 }
Eric Laurent733ce942017-12-07 12:18:25 -08003644 status_t status = outputDesc->start();
3645 if (status != NO_ERROR) {
3646 return status;
3647 }
3648
Eric Laurentd60560a2015-04-10 11:31:20 -07003649 // create a special patch with no sink and two sources:
3650 // - the second source indicates to PatchPanel through which output mix this patch should
3651 // be connected as well as the stream type for volume control
3652 // - the sink is defined by whatever output device is currently selected for the output
3653 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003654 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003655 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003656 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003657 &afPatchHandle,
3658 0);
3659 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3660 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003661 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003662 if (status != NO_ERROR) {
3663 ALOGW("%s patch panel could not connect device patch, error %d",
3664 __FUNCTION__, status);
3665 return INVALID_OPERATION;
3666 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003667
3668 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3669 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3670 return INVALID_OPERATION;
3671 }
3672 outputDesc->addClient(sourceDesc);
3673
Eric Laurentd60560a2015-04-10 11:31:20 -07003674 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003675 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003676
3677 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003678 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003679 return status;
3680 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003681 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003682 if (delayMs != 0) {
3683 usleep(delayMs * 1000);
3684 }
3685 }
3686
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003687 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3688 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003689
3690 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003691}
3692
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003693status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003694{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003695 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3696 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003697 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003698 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003699 return BAD_VALUE;
3700 }
3701 status_t status = disconnectAudioSource(sourceDesc);
3702
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003703 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003704 return status;
3705}
3706
Andy Hung2ddee192015-12-18 17:34:44 -08003707status_t AudioPolicyManager::setMasterMono(bool mono)
3708{
3709 if (mMasterMono == mono) {
3710 return NO_ERROR;
3711 }
3712 mMasterMono = mono;
3713 // if enabling mono we close all offloaded devices, which will invalidate the
3714 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3715 // for recreating the new AudioTrack as non-offloaded PCM.
3716 //
3717 // If disabling mono, we leave all tracks as is: we don't know which clients
3718 // and tracks are able to be recreated as offloaded. The next "song" should
3719 // play back offloaded.
3720 if (mMasterMono) {
3721 Vector<audio_io_handle_t> offloaded;
3722 for (size_t i = 0; i < mOutputs.size(); ++i) {
3723 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3724 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3725 offloaded.push(desc->mIoHandle);
3726 }
3727 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003728 for (const auto& handle : offloaded) {
3729 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003730 }
3731 }
3732 // update master mono for all remaining outputs
3733 for (size_t i = 0; i < mOutputs.size(); ++i) {
3734 updateMono(mOutputs.keyAt(i));
3735 }
3736 return NO_ERROR;
3737}
3738
3739status_t AudioPolicyManager::getMasterMono(bool *mono)
3740{
3741 *mono = mMasterMono;
3742 return NO_ERROR;
3743}
3744
Eric Laurentac9cef52017-06-09 15:46:26 -07003745float AudioPolicyManager::getStreamVolumeDB(
3746 audio_stream_type_t stream, int index, audio_devices_t device)
3747{
3748 return computeVolume(stream, index, device);
3749}
3750
jiabin81772902018-04-02 17:52:27 -07003751status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3752 audio_format_t *surroundFormats,
3753 bool *surroundFormatsEnabled,
3754 bool reported)
3755{
3756 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3757 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3758 return BAD_VALUE;
3759 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003760 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3761 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003762
3763 size_t formatsWritten = 0;
3764 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003765 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003766 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003767 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003768 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003769 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3770 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3771 FormatVector supportedFormats =
3772 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3773 for (size_t j = 0; j < supportedFormats.size(); j++) {
3774 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3775 formats.insert(supportedFormats[j]);
3776 } else {
3777 for (const auto& pair : mConfig.getSurroundFormats()) {
3778 if (pair.second.count(supportedFormats[j]) != 0) {
3779 formats.insert(pair.first);
3780 break;
3781 }
3782 }
3783 }
3784 }
jiabin81772902018-04-02 17:52:27 -07003785 }
3786 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003787 for (const auto& pair : mConfig.getSurroundFormats()) {
3788 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003789 }
3790 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003791 *numSurroundFormats = formats.size();
3792 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3793 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003794 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003795 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003796 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003797 bool formatEnabled = true;
3798 switch (forceUse) {
3799 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3800 formatEnabled = mManualSurroundFormats.count(format) != 0;
3801 break;
3802 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3803 formatEnabled = false;
3804 break;
3805 default: // AUTO or ALWAYS => true
3806 break;
jiabin81772902018-04-02 17:52:27 -07003807 }
3808 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3809 }
jiabin81772902018-04-02 17:52:27 -07003810 }
3811 return NO_ERROR;
3812}
3813
3814status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3815{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003816 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003817 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3818 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003819 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003820 return BAD_VALUE;
3821 }
3822
Mikhail Naganov100f0122018-11-29 11:22:16 -08003823 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3824 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003825 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003826 return INVALID_OPERATION;
3827 }
3828
Mikhail Naganov100f0122018-11-29 11:22:16 -08003829 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003830 return NO_ERROR;
3831 }
3832
Mikhail Naganov100f0122018-11-29 11:22:16 -08003833 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003834 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003835 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003836 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003837 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003838 }
3839 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003840 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003841 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003842 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003843 }
3844 }
3845
3846 sp<SwAudioOutputDescriptor> outputDesc;
3847 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003848 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003849 AUDIO_DEVICE_OUT_HDMI);
3850 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3851 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003852 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003853 String8 name = hdmiOutputDevices[i]->getName();
3854 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3855 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3856 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003857 name.c_str(),
3858 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003859 if (status != NO_ERROR) {
3860 continue;
3861 }
3862 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3863 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3864 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003865 name.c_str(),
3866 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003867 profileUpdated |= (status == NO_ERROR);
3868 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003869 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003870 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003871 AUDIO_DEVICE_IN_HDMI);
3872 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3873 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003874 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003875 String8 name = hdmiInputDevices[i]->getName();
3876 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3877 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3878 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003879 name.c_str(),
3880 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003881 if (status != NO_ERROR) {
3882 continue;
3883 }
3884 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3885 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3886 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003887 name.c_str(),
3888 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003889 profileUpdated |= (status == NO_ERROR);
3890 }
3891
jiabin81772902018-04-02 17:52:27 -07003892 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003893 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003894 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003895 }
3896
3897 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3898}
3899
Eric Laurentf32108e2018-10-04 17:22:04 -07003900void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003901{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003902 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003903
Eric Laurenta9f86652018-11-28 17:23:11 -08003904 for (size_t i = 0; i < mInputs.size(); i++) {
3905 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3906 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003907 for (const auto& client : clients) {
3908 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003909 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003910 }
3911 }
3912 }
3913}
3914
jiabin6012f912018-11-02 17:06:30 -07003915bool AudioPolicyManager::isHapticPlaybackSupported()
3916{
3917 for (const auto& hwModule : mHwModules) {
3918 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3919 for (const auto &outProfile : outputProfiles) {
3920 struct audio_port audioPort;
3921 outProfile->toAudioPort(&audioPort);
3922 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3923 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3924 return true;
3925 }
3926 }
3927 }
3928 }
3929 return false;
3930}
3931
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003932status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003933{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003934 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003935
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003936 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003937 if (patchDesc == 0) {
3938 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003939 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003940 return BAD_VALUE;
3941 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003942 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003943
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003944 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003945 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003946 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003947 if (status == NO_ERROR) {
3948 swOutputDesc->stop();
3949 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003950 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3951 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003952 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003953 if (hwOutputDesc != 0) {
3954 // release patch between src device and output device
3955 // close Hwoutput and remove from mHwOutputs
3956 } else {
3957 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3958 }
3959 }
3960 return NO_ERROR;
3961}
3962
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003963sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003964 audio_io_handle_t output, routing_strategy strategy)
3965{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003966 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003967 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003968 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3969 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003970 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003971 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003972 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3973 source = sourceDesc;
3974 break;
3975 }
3976 }
3977 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003978}
3979
Eric Laurente552edb2014-03-10 17:42:56 -07003980// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003981// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003982// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003983uint32_t AudioPolicyManager::nextAudioPortGeneration()
3984{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003985 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003986}
3987
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003988// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3989static const char *kConfigLocationList[] =
3990 {"/odm/etc", "/vendor/etc", "/system/etc"};
3991static const int kConfigLocationListSize =
3992 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3993
3994static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3995 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003996 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003997 status_t ret;
3998
Petri Gyntherf497f292018-04-17 18:46:10 -07003999 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
4000 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4001 // A2DP offload supported but disabled: try to use special XML file
4002 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4003 }
4004 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4005
4006 for (const char* fileName : fileNames) {
4007 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004008 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4009 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004010 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004011 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004012 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004013 return ret;
4014 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004015 }
4016 }
4017 return ret;
4018}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004019
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004020AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4021 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004022 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004023 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004024 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004025 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004027 mVolumeCurves(new VolumeCurvesCollection()),
4028 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004029 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004030 mAudioPortGeneration(1),
4031 mBeaconMuteRefCount(0),
4032 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004033 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004034 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004035 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004036 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004037{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004038}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004039
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004040AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4041 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4042{
4043 loadConfig();
4044 initialize();
4045}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004046
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004047// This check is to catch any legacy platform updating to Q without having
4048// switched to XML since its deprecation on O.
4049// TODO: after Q release, remove this check and flag as XML is now the only
4050// option and all legacy platform should have transitioned to XML.
4051#ifndef USE_XML_AUDIO_POLICY_CONF
4052#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004053#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004054
4055void AudioPolicyManager::loadConfig() {
4056 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004057 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004058 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004059 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004060}
4061
4062status_t AudioPolicyManager::initialize() {
4063 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004064
4065 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004066 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4067 if (!engineInstance) {
4068 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004069 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004070 }
4071 // Retrieve the Policy Manager Interface
4072 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4073 if (mEngine == NULL) {
4074 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004075 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004076 }
4077 mEngine->setObserver(this);
4078 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004079 if (status != NO_ERROR) {
4080 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4081 return status;
4082 }
François Gaffie2110e042015-03-24 08:41:51 +01004083
Eric Laurent3a4311c2014-03-17 12:00:47 -07004084 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004085 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004086 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004087 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004088 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4089 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004090 continue;
4091 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004092 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004093 // open all output streams needed to access attached devices
4094 // except for direct output streams that are only opened when they are actually
4095 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004097 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004098 if (!outProfile->canOpenNewIo()) {
4099 ALOGE("Invalid Output profile max open count %u for profile %s",
4100 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4101 continue;
4102 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004103 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004104 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004105 continue;
4106 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004107 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004108 mTtsOutputAvailable = true;
4109 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004110
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004111 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004112 continue;
4113 }
François Gaffie11d30102018-11-02 16:09:09 +01004114 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4115 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4116 sp<DeviceDescriptor> supportedDevice = 0;
4117 if (supportedDevices.contains(mDefaultOutputDevice)) {
4118 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004119 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004120 // choose first device present in profile's SupportedDevices also part of
4121 // mAvailableOutputDevices.
4122 if (availProfileDevices.isEmpty()) {
4123 continue;
4124 }
4125 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004126 }
François Gaffie11d30102018-11-02 16:09:09 +01004127 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004128 continue;
4129 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004130 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4131 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004132 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004133 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4134 AUDIO_STREAM_DEFAULT,
4135 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004136 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004137 ALOGW("Cannot open output stream for devices %s on hw module %s",
4138 supportedDevice->toString().c_str(), hwModule->getName());
4139 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004140 }
François Gaffie11d30102018-11-02 16:09:09 +01004141 for (const auto &device : availProfileDevices) {
4142 // give a valid ID to an attached device once confirmed it is reachable
4143 if (!device->isAttached()) {
4144 device->attach(hwModule);
4145 }
4146 }
4147 if (mPrimaryOutput == 0 &&
4148 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4149 mPrimaryOutput = outputDesc;
4150 }
4151 addOutput(output, outputDesc);
4152 setOutputDevices(outputDesc,
4153 DeviceVector(supportedDevice),
4154 true,
4155 0,
4156 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 // open input streams needed to access attached devices to validate
4159 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004160 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004161 if (!inProfile->canOpenNewIo()) {
4162 ALOGE("Invalid Input profile max open count %u for profile %s",
4163 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4164 continue;
4165 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004166 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004167 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 continue;
4169 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004170 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004171 // available input devices
4172 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4173 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4174 if (availProfileDevices.isEmpty()) {
4175 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004176 continue;
4177 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004178 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004179 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004180
Eric Laurentd78f1532014-09-16 16:38:20 -07004181 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004182 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004183 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004184 AUDIO_SOURCE_MIC,
4185 AUDIO_INPUT_FLAG_NONE,
4186 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004187 if (status != NO_ERROR) {
4188 ALOGW("Cannot open input stream for device %s on hw module %s",
4189 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004190 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004191 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004192 }
François Gaffie11d30102018-11-02 16:09:09 +01004193 for (const auto &device : availProfileDevices) {
4194 // give a valid ID to an attached device once confirmed it is reachable
4195 if (!device->isAttached()) {
4196 device->attach(hwModule);
4197 device->importAudioPort(inProfile, true);
4198 }
4199 }
4200 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004201 }
4202 }
4203 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004204 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004205 for (size_t i = 0; i < devices.size();) {
4206 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004207 if (!device->isAttached()) {
4208 ALOGW("device %s is unreachable", device->toString().c_str());
4209 devices.remove(device);
4210 continue;
4211 }
4212 // Device is now validated and can be appended to the available devices of the engine
4213 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004214 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004215 }
François Gaffie11d30102018-11-02 16:09:09 +01004216 };
4217 checkAndSetAvailable(mAvailableOutputDevices);
4218 checkAndSetAvailable(mAvailableInputDevices);
4219
Eric Laurent3a4311c2014-03-17 12:00:47 -07004220 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004221 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4222 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4223 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004224 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004225 }
jiabin9ff780e2018-03-19 18:19:52 -07004226 // If microphones address is empty, set it according to device type
4227 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004228 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004229 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004230 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004231 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004232 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004233 }
4234 }
4235 }
Eric Laurente552edb2014-03-10 17:42:56 -07004236
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004237 if (mPrimaryOutput == 0) {
4238 ALOGE("Failed to open primary output");
4239 status = NO_INIT;
4240 }
Eric Laurente552edb2014-03-10 17:42:56 -07004241
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004242 // Silence ALOGV statements
4243 property_set("log.tag." LOG_TAG, "D");
4244
Eric Laurente552edb2014-03-10 17:42:56 -07004245 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004246 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004247}
4248
Eric Laurente0720872014-03-11 09:30:41 -07004249AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004250{
Eric Laurente552edb2014-03-10 17:42:56 -07004251 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004252 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004253 }
4254 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004255 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004256 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004257 mAvailableOutputDevices.clear();
4258 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004259 mOutputs.clear();
4260 mInputs.clear();
4261 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004262 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004263 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004264}
4265
Eric Laurente0720872014-03-11 09:30:41 -07004266status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004267{
Eric Laurent87ffa392015-05-22 10:32:38 -07004268 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004269}
4270
Eric Laurente552edb2014-03-10 17:42:56 -07004271// ---
4272
Eric Laurent98e38192018-02-15 18:31:53 -08004273void AudioPolicyManager::addOutput(audio_io_handle_t output,
4274 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004275{
Eric Laurent1c333e22014-05-20 10:48:17 -07004276 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004277 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004278 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004279 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004280 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004281}
4282
François Gaffie53615e22015-03-19 09:24:12 +01004283void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4284{
4285 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004286 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004287}
4288
Eric Laurent98e38192018-02-15 18:31:53 -08004289void AudioPolicyManager::addInput(audio_io_handle_t input,
4290 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004291{
Eric Laurent1c333e22014-05-20 10:48:17 -07004292 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004293 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004294}
Eric Laurente552edb2014-03-10 17:42:56 -07004295
François Gaffie11d30102018-11-02 16:09:09 +01004296status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004297 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004298 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004299{
François Gaffie11d30102018-11-02 16:09:09 +01004300 audio_devices_t deviceType = device->type();
4301 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004302 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004303
François Gaffie11d30102018-11-02 16:09:09 +01004304 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004305 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004306 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004307 }
Eric Laurente552edb2014-03-10 17:42:56 -07004308
Eric Laurent3b73df72014-03-11 09:06:29 -07004309 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004310 // first list already open outputs that can be routed to this device
4311 for (size_t i = 0; i < mOutputs.size(); i++) {
4312 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004313 if (!desc->isDuplicated() && desc->supportsDevice(device)
4314 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004315 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4316 mOutputs.keyAt(i), device->toString().c_str());
4317 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004318 }
4319 }
4320 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004321 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004322 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004323 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4324 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004325 if (profile->supportsDevice(device)) {
4326 profiles.add(profile);
4327 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4328 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004329 }
4330 }
4331 }
4332
Eric Laurent7b279bb2015-12-14 10:18:23 -08004333 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004334
Eric Laurente552edb2014-03-10 17:42:56 -07004335 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004336 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004337 return BAD_VALUE;
4338 }
4339
4340 // open outputs for matching profiles if needed. Direct outputs are also opened to
4341 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4342 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004343 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004344
4345 // nothing to do if one output is already opened for this profile
4346 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004347 for (j = 0; j < outputs.size(); j++) {
4348 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004349 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004350 // matching profile: save the sample rates, format and channel masks supported
4351 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004352 if (audio_device_is_digital(deviceType)) {
4353 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004354 }
Eric Laurente552edb2014-03-10 17:42:56 -07004355 break;
4356 }
4357 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004358 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 continue;
4360 }
4361
Eric Laurent3974e3b2017-12-07 17:58:43 -08004362 if (!profile->canOpenNewIo()) {
4363 ALOGW("Max Output number %u already opened for this profile %s",
4364 profile->maxOpenCount, profile->getTagName().c_str());
4365 continue;
4366 }
4367
Eric Laurent83efe1c2017-07-09 16:51:08 -07004368 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004369 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004370 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004371 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004372 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004373 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004374
Eric Laurentfe231122017-11-17 17:48:06 -08004375 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004376 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004377 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004378 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004379 mpClientInterface->setParameters(output, String8(param));
4380 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004381 }
François Gaffie11d30102018-11-02 16:09:09 +01004382 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004383 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004384 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004385 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004386 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004387 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004388 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004389 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004390 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4391 profile->pickAudioProfile(
4392 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004393 config.offload_info.sample_rate = config.sample_rate;
4394 config.offload_info.channel_mask = config.channel_mask;
4395 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004396
François Gaffie11d30102018-11-02 16:09:09 +01004397 status_t status = desc->open(&config, DeviceVector(device),
4398 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004399 AUDIO_OUTPUT_FLAG_NONE, &output);
4400 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004401 output = AUDIO_IO_HANDLE_NONE;
4402 }
Eric Laurentd4692962014-05-05 18:13:44 -07004403 }
4404
Eric Laurentcf2c0212014-07-25 16:20:43 -07004405 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004406 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004407 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004408 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004409 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4410 policyMix->setOutput(desc);
4411 desc->mPolicyMix = policyMix->getMix();
4412 } else {
4413 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004414 address.string());
4415 }
François Gaffie036e1e92015-03-19 10:16:24 +01004416
Eric Laurent87ffa392015-05-22 10:32:38 -07004417 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4418 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004419 // no duplicated output for direct outputs and
4420 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004421 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004422
Eric Laurentd4692962014-05-05 18:13:44 -07004423 //TODO: configure audio effect output stage here
4424
4425 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004426 sp<SwAudioOutputDescriptor> dupOutputDesc =
4427 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4428 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4429 &duplicatedOutput);
4430 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004431 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004432 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004433 } else {
4434 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004435 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004436 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004437 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004438 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004439 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004440 }
Eric Laurente552edb2014-03-10 17:42:56 -07004441 }
4442 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004443 } else {
4444 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004445 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004446 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004447 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004448 profiles.removeAt(profile_index);
4449 profile_index--;
4450 } else {
4451 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004452 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004453 if (audio_device_is_digital(deviceType)) {
4454 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004455 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004456
François Gaffie11d30102018-11-02 16:09:09 +01004457 if (device_distinguishes_on_address(deviceType)) {
4458 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4459 device->toString().c_str());
4460 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4461 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004462 }
Eric Laurente552edb2014-03-10 17:42:56 -07004463 ALOGV("checkOutputsForDevice(): adding output %d", output);
4464 }
4465 }
4466
4467 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004468 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004469 return BAD_VALUE;
4470 }
Eric Laurentd4692962014-05-05 18:13:44 -07004471 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004472 // check if one opened output is not needed any more after disconnecting one device
4473 for (size_t i = 0; i < mOutputs.size(); i++) {
4474 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004475 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004476 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004477 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4478 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004479 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004480 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004481 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4482 mOutputs.keyAt(i));
4483 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004484 }
Eric Laurente552edb2014-03-10 17:42:56 -07004485 }
4486 }
Eric Laurentd4692962014-05-05 18:13:44 -07004487 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004488 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004489 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4490 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004491 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004492 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004493 "clearing direct output profile %zu on module %s",
4494 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004495 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004496 }
4497 }
4498 }
4499 }
4500 return NO_ERROR;
4501}
4502
François Gaffie11d30102018-11-02 16:09:09 +01004503status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004504 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004505 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004506{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004507 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004508
François Gaffie11d30102018-11-02 16:09:09 +01004509 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004510 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004511 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004512 }
4513
Eric Laurentd4692962014-05-05 18:13:44 -07004514 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4515 // first list already open inputs that can be routed to this device
4516 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4517 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004518 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004519 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4520 inputs.add(mInputs.keyAt(input_index));
4521 }
4522 }
4523
4524 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004525 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004526 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004527 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004528 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004529 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004530 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004531
François Gaffie11d30102018-11-02 16:09:09 +01004532 if (profile->supportsDevice(device)) {
4533 profiles.add(profile);
4534 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4535 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004536 }
4537 }
4538 }
4539
4540 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004541 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004542 return BAD_VALUE;
4543 }
4544
4545 // open inputs for matching profiles if needed. Direct inputs are also opened to
4546 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4547 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4548
Eric Laurent1c333e22014-05-20 10:48:17 -07004549 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004550
Eric Laurentd4692962014-05-05 18:13:44 -07004551 // nothing to do if one input is already opened for this profile
4552 size_t input_index;
4553 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4554 desc = mInputs.valueAt(input_index);
4555 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004556 if (audio_device_is_digital(device->type())) {
4557 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004558 }
Eric Laurentd4692962014-05-05 18:13:44 -07004559 break;
4560 }
4561 }
4562 if (input_index != mInputs.size()) {
4563 continue;
4564 }
4565
Eric Laurent3974e3b2017-12-07 17:58:43 -08004566 if (!profile->canOpenNewIo()) {
4567 ALOGW("Max Input number %u already opened for this profile %s",
4568 profile->maxOpenCount, profile->getTagName().c_str());
4569 continue;
4570 }
4571
Eric Laurentfe231122017-11-17 17:48:06 -08004572 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004573 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004574 status_t status = desc->open(nullptr,
4575 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004576 AUDIO_SOURCE_MIC,
4577 AUDIO_INPUT_FLAG_NONE,
4578 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004579
Eric Laurentcf2c0212014-07-25 16:20:43 -07004580 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004581 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004582 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004583 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004584 mpClientInterface->setParameters(input, String8(param));
4585 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004586 }
François Gaffie11d30102018-11-02 16:09:09 +01004587 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004588 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004589 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004590 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004591 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004592 }
4593
4594 if (input != 0) {
4595 addInput(input, desc);
4596 }
4597 } // endif input != 0
4598
Eric Laurentcf2c0212014-07-25 16:20:43 -07004599 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004600 ALOGW("%s could not open input for device %s", __func__,
4601 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004602 profiles.removeAt(profile_index);
4603 profile_index--;
4604 } else {
4605 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004606 if (audio_device_is_digital(device->type())) {
4607 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004608 }
Eric Laurentd4692962014-05-05 18:13:44 -07004609 ALOGV("checkInputsForDevice(): adding input %d", input);
4610 }
4611 } // end scan profiles
4612
4613 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004614 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004615 return BAD_VALUE;
4616 }
4617 } else {
4618 // Disconnect
4619 // check if one opened input is not needed any more after disconnecting one device
4620 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4621 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004622 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004623 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4624 mInputs.keyAt(input_index));
4625 inputs.add(mInputs.keyAt(input_index));
4626 }
4627 }
4628 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004629 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004630 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004631 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004632 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004633 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004634 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004635 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4636 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004637 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004638 }
4639 }
4640 }
4641 } // end disconnect
4642
4643 return NO_ERROR;
4644}
4645
4646
Eric Laurente0720872014-03-11 09:30:41 -07004647void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004648{
4649 ALOGV("closeOutput(%d)", output);
4650
Eric Laurentc75307b2015-03-17 15:29:32 -07004651 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004652 if (outputDesc == NULL) {
4653 ALOGW("closeOutput() unknown output %d", output);
4654 return;
4655 }
François Gaffie036e1e92015-03-19 10:16:24 +01004656 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004657
Eric Laurente552edb2014-03-10 17:42:56 -07004658 // look for duplicated outputs connected to the output being removed.
4659 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 if (dupOutputDesc->isDuplicated() &&
4662 (dupOutputDesc->mOutput1 == outputDesc ||
4663 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004664 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004665 if (dupOutputDesc->mOutput1 == outputDesc) {
4666 outputDesc2 = dupOutputDesc->mOutput2;
4667 } else {
4668 outputDesc2 = dupOutputDesc->mOutput1;
4669 }
4670 // As all active tracks on duplicated output will be deleted,
4671 // and as they were also referenced on the other output, the reference
4672 // count for their stream type must be adjusted accordingly on
4673 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004674 const bool wasActive = outputDesc2->isActive();
4675 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4676 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004677 }
Eric Laurent733ce942017-12-07 12:18:25 -08004678 // stop() will be a no op if the output is still active but is needed in case all
4679 // active streams refcounts where cleared above
4680 if (wasActive) {
4681 outputDesc2->stop();
4682 }
Eric Laurente552edb2014-03-10 17:42:56 -07004683 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4684 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4685
4686 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004687 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004688 }
4689 }
4690
Eric Laurent05b90f82014-08-27 15:32:29 -07004691 nextAudioPortGeneration();
4692
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004693 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004694 if (index >= 0) {
4695 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004696 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004697 mAudioPatches.removeItemsAt(index);
4698 mpClientInterface->onAudioPatchListUpdate();
4699 }
4700
Eric Laurentfe231122017-11-17 17:48:06 -08004701 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004702
François Gaffie53615e22015-03-19 09:24:12 +01004703 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004704 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004705
4706 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4707 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004708 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004709 bool directOutputOpen = false;
4710 for (size_t i = 0; i < mOutputs.size(); i++) {
4711 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4712 directOutputOpen = true;
4713 break;
4714 }
4715 }
4716 if (!directOutputOpen) {
4717 ALOGV("no direct outputs open, reset MSD patch");
4718 setMsdPatch();
4719 }
4720 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004721}
4722
4723void AudioPolicyManager::closeInput(audio_io_handle_t input)
4724{
4725 ALOGV("closeInput(%d)", input);
4726
4727 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4728 if (inputDesc == NULL) {
4729 ALOGW("closeInput() unknown input %d", input);
4730 return;
4731 }
4732
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004734
François Gaffie11d30102018-11-02 16:09:09 +01004735 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004736 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004737 if (index >= 0) {
4738 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004739 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004740 mAudioPatches.removeItemsAt(index);
4741 mpClientInterface->onAudioPatchListUpdate();
4742 }
4743
Eric Laurentfe231122017-11-17 17:48:06 -08004744 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004745 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004746
François Gaffie11d30102018-11-02 16:09:09 +01004747 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4748 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004749 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4750 SoundTrigger::setCaptureState(false);
4751 }
Eric Laurente552edb2014-03-10 17:42:56 -07004752}
4753
François Gaffie11d30102018-11-02 16:09:09 +01004754SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4755 const DeviceVector &devices,
4756 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004757{
4758 SortedVector<audio_io_handle_t> outputs;
4759
François Gaffie11d30102018-11-02 16:09:09 +01004760 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004761 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004762 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004763 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004764 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004765 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4766 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004767 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004768 outputs.add(openOutputs.keyAt(i));
4769 }
4770 }
4771 return outputs;
4772}
4773
Mikhail Naganov37977152018-07-11 15:54:44 -07004774void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4775{
4776 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4777 // output is suspended before any tracks are moved to it
4778 checkA2dpSuspend();
4779 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004780 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004781 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004782 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004783 setMsdPatch();
4784 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004785}
4786
Eric Laurente0720872014-03-11 09:30:41 -07004787void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004788{
François Gaffie11d30102018-11-02 16:09:09 +01004789 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4790 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4791 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4792 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004793
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004794 // also take into account external policy-related changes: add all outputs which are
4795 // associated with policies in the "before" and "after" output vectors
4796 ALOGVV("checkOutputForStrategy(): policy related outputs");
4797 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004798 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004799 if (desc != 0 && desc->mPolicyMix != NULL) {
4800 srcOutputs.add(desc->mIoHandle);
4801 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4802 }
4803 }
4804 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004805 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004806 if (desc != 0 && desc->mPolicyMix != NULL) {
4807 dstOutputs.add(desc->mIoHandle);
4808 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4809 }
4810 }
4811
Francois Gaffie716e1432019-01-14 16:58:59 +01004812 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004813 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4814 // audio from invalidated tracks will be rendered when unmuting
4815 uint32_t maxLatency = 0;
4816 for (audio_io_handle_t srcOut : srcOutputs) {
4817 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4818 if (desc != 0 && maxLatency < desc->latency()) {
4819 maxLatency = desc->latency();
4820 }
4821 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004822 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4823 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4824 std::to_string(srcOutputs[0]).c_str(),
4825 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004826 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004827 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004828 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4829 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004830 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004831 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4832 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004833 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004834 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004835 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004836 if (source != 0){
4837 connectAudioSource(source);
4838 }
Eric Laurente552edb2014-03-10 17:42:56 -07004839 }
4840
4841 // Move effects associated to this strategy from previous output to new output
4842 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004843 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004844 }
4845 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004846 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004847 if (getStrategy((audio_stream_type_t)i) == strategy) {
4848 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004849 }
4850 }
4851 }
4852}
4853
Eric Laurente0720872014-03-11 09:30:41 -07004854void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004855{
François Gaffie2110e042015-03-24 08:41:51 +01004856 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004857 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004858 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004859 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004860 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004861 checkOutputForStrategy(STRATEGY_SONIFICATION);
4862 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 checkOutputForStrategy(STRATEGY_MEDIA);
4865 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004866 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004867}
4868
Eric Laurente0720872014-03-11 09:30:41 -07004869void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004870{
François Gaffie53615e22015-03-19 09:24:12 +01004871 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004872 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004873 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004874 return;
4875 }
4876
Eric Laurent3a4311c2014-03-17 12:00:47 -07004877 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004878 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4879 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4880 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004881
4882 // if suspended, restore A2DP output if:
4883 // ((SCO device is NOT connected) ||
4884 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4885 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004886 //
Eric Laurentf732e072016-08-03 19:30:28 -07004887 // if not suspended, suspend A2DP output if:
4888 // (SCO device is connected) &&
4889 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4890 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004891 //
4892 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004893 if (!isScoConnected ||
4894 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4895 AUDIO_POLICY_FORCE_BT_SCO) &&
4896 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4897 AUDIO_POLICY_FORCE_BT_SCO) &&
4898 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004899 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004900
4901 mpClientInterface->restoreOutput(a2dpOutput);
4902 mA2dpSuspended = false;
4903 }
4904 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004905 if (isScoConnected &&
4906 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4907 AUDIO_POLICY_FORCE_BT_SCO) ||
4908 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4909 AUDIO_POLICY_FORCE_BT_SCO) ||
4910 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004911 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004912
4913 mpClientInterface->suspendOutput(a2dpOutput);
4914 mA2dpSuspended = true;
4915 }
4916 }
4917}
4918
Eric Laurent97ac8712018-07-27 18:59:02 -07004919template <class IoDescriptor, class Filter>
4920sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4921 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4922{
4923 auto activeClients = desc->clientsList(true /*activeOnly*/);
4924 auto activeClientsWithRoute =
4925 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4926 active = activeClients.size() > 0;
4927 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4928 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4929 }
4930 return nullptr;
4931}
4932
4933template <class IoCollection, class Filter>
4934sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4935 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4936{
4937 sp<DeviceDescriptor> device;
4938 for (size_t i = 0; i < ioCollection.size(); i++) {
4939 auto desc = ioCollection.valueAt(i);
4940 bool active;
4941 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4942 if (active && curDevice == nullptr) {
4943 return nullptr;
4944 } else if (curDevice != nullptr) {
4945 device = curDevice;
4946 }
4947 }
4948 return device;
4949}
4950
François Gaffie11d30102018-11-02 16:09:09 +01004951DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4952 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004953{
François Gaffie11d30102018-11-02 16:09:09 +01004954 DeviceVector devices;
4955
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004956 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 if (index >= 0) {
4958 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4959 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004960 ALOGV("%s device %s forced by patch %d", __func__,
4961 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4962 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 }
4964 }
4965
Eric Laurent97ac8712018-07-27 18:59:02 -07004966 // Honor explicit routing requests only if no client using default routing is active on this
4967 // input: a specific app can not force routing for other apps by setting a preferred device.
4968 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004969 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004970 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004971 if (device != nullptr) {
4972 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004973 }
4974
François Gaffiea807ef92018-11-05 10:44:33 +01004975 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
4976 // of setForceUse / Default Bus device here
4977 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
4978 if (device != nullptr) {
4979 return DeviceVector(device);
4980 }
4981
Eric Laurente552edb2014-03-10 17:42:56 -07004982 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004983 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004984 // use device for strategy enforced audible
4985 // 2: we are in call or the strategy phone is active on the output:
4986 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004987 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004988 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004989 // 4: the strategy for enforced audible is active but not enforced on the output:
4990 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004991 // 5: the strategy accessibility is active on the output:
4992 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004993 // 6: the strategy "respectful" sonification is active on the output:
4994 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004995 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004996 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004997 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004998 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004999 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005000 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07005001
5002 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
5003 // with a refined rule considering mutually exclusive devices (using same backend)
5004 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01005005 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005006 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01005007 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005008 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07005009 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005010 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08005011 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01005012 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07005013 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005014 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005015 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01005016 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005017 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01005018 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005019 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01005020 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005021 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01005022 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005023 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01005024 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005025 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01005026 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005027 }
5028
François Gaffie11d30102018-11-02 16:09:09 +01005029 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
5030 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005031}
5032
François Gaffie11d30102018-11-02 16:09:09 +01005033sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5034 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005035{
François Gaffie11d30102018-11-02 16:09:09 +01005036 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005037
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005038 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 if (index >= 0) {
5040 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5041 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005042 ALOGV("getNewInputDevice() device %s forced by patch %d",
5043 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5044 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 }
5046 }
5047
Eric Laurent97ac8712018-07-27 18:59:02 -07005048 // Honor explicit routing requests only if no client using default routing is active on this
5049 // input: a specific app can not force routing for other apps by setting a preferred device.
5050 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005051 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5052 if (device != nullptr) {
5053 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005054 }
5055
Eric Laurentdc95a252018-04-12 12:46:56 -07005056 // If we are not in call and no client is active on this input, this methods returns
5057 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005058 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5059 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5060 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005061 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005062 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5063 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005064 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005065
Eric Laurente552edb2014-03-10 17:42:56 -07005066 return device;
5067}
5068
Eric Laurent794fde22016-03-11 09:50:45 -08005069bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5070 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005071 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005072}
5073
Eric Laurente0720872014-03-11 09:30:41 -07005074uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005075 return (uint32_t)getStrategy(stream);
5076}
5077
Eric Laurente0720872014-03-11 09:30:41 -07005078audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005079 // By checking the range of stream before calling getStrategy, we avoid
5080 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5081 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005082 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005083 return AUDIO_DEVICE_NONE;
5084 }
François Gaffie11d30102018-11-02 16:09:09 +01005085 DeviceVector activeDevices;
5086 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005087 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5088 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005089 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 }
Eric Laurent794fde22016-03-11 09:50:45 -08005091 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005092 DeviceVector curDevices =
5093 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5094 devices.merge(curDevices);
5095 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005096 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005097 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005098 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005099 }
5100 }
Eric Laurente552edb2014-03-10 17:42:56 -07005101 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005102
Eric Laurentb0688d62018-08-14 15:49:18 -07005103 // Favor devices selected on active streams if any to report correct device in case of
5104 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005105 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005106 devices = activeDevices;
5107 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005108 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5109 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005110 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5111 if (!speakerSafeDevices.isEmpty()) {
5112 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5113 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005114 }
François Gaffie11d30102018-11-02 16:09:09 +01005115 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005116}
5117
François Gaffie2110e042015-03-24 08:41:51 +01005118routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5119{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005120 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005121 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005122}
5123
Eric Laurent97ac8712018-07-27 18:59:02 -07005124routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005125 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005126 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005127 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005128 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005129 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005130 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005131 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005132 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005133 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005134}
5135
Eric Laurente0720872014-03-11 09:30:41 -07005136void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005137 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005138 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005139 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5140 updateDevicesAndOutputs();
5141 break;
5142 default:
5143 break;
5144 }
5145}
5146
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005147uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005148
5149 // skip beacon mute management if a dedicated TTS output is available
5150 if (mTtsOutputAvailable) {
5151 return 0;
5152 }
5153
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005154 switch(event) {
5155 case STARTING_OUTPUT:
5156 mBeaconMuteRefCount++;
5157 break;
5158 case STOPPING_OUTPUT:
5159 if (mBeaconMuteRefCount > 0) {
5160 mBeaconMuteRefCount--;
5161 }
5162 break;
5163 case STARTING_BEACON:
5164 mBeaconPlayingRefCount++;
5165 break;
5166 case STOPPING_BEACON:
5167 if (mBeaconPlayingRefCount > 0) {
5168 mBeaconPlayingRefCount--;
5169 }
5170 break;
5171 }
5172
5173 if (mBeaconMuteRefCount > 0) {
5174 // any playback causes beacon to be muted
5175 return setBeaconMute(true);
5176 } else {
5177 // no other playback: unmute when beacon starts playing, mute when it stops
5178 return setBeaconMute(mBeaconPlayingRefCount == 0);
5179 }
5180}
5181
5182uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5183 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5184 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5185 // keep track of muted state to avoid repeating mute/unmute operations
5186 if (mBeaconMuted != mute) {
5187 // mute/unmute AUDIO_STREAM_TTS on all outputs
5188 ALOGV("\t muting %d", mute);
5189 uint32_t maxLatency = 0;
5190 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005191 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005192 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005193 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005194 0 /*delay*/, AUDIO_DEVICE_NONE);
5195 const uint32_t latency = desc->latency() * 2;
5196 if (latency > maxLatency) {
5197 maxLatency = latency;
5198 }
5199 }
5200 mBeaconMuted = mute;
5201 return maxLatency;
5202 }
5203 return 0;
5204}
5205
François Gaffie11d30102018-11-02 16:09:09 +01005206DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005207{
Eric Laurent97ac8712018-07-27 18:59:02 -07005208 // Honor explicit routing requests only if all active clients have a preferred route in which
5209 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005210 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5211 if (device != nullptr) {
5212 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005213 }
5214
Eric Laurente552edb2014-03-10 17:42:56 -07005215 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005216 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5217 mDevicesForStrategy[strategy].toString().c_str());
5218 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005219 }
François Gaffie11d30102018-11-02 16:09:09 +01005220 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005221}
5222
Eric Laurente0720872014-03-11 09:30:41 -07005223void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005224{
5225 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005226 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 }
5228 mPreviousOutputs = mOutputs;
5229}
5230
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005231uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005232 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005233 uint32_t delayMs)
5234{
5235 // mute/unmute strategies using an incompatible device combination
5236 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5237 // if unmuting, unmute only after the specified delay
5238 if (outputDesc->isDuplicated()) {
5239 return 0;
5240 }
5241
5242 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005243 audio_devices_t deviceType = outputDesc->devices().types();
5244 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005245
5246 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005247 audio_devices_t curDeviceType =
5248 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5249 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5250 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005251 bool doMute = false;
5252
5253 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5254 doMute = true;
5255 outputDesc->mStrategyMutedByDevice[i] = true;
5256 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5257 doMute = true;
5258 outputDesc->mStrategyMutedByDevice[i] = false;
5259 }
Eric Laurent99401132014-05-07 19:48:15 -07005260 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005261 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005262 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005263 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005264 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005265 continue;
5266 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005267 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005268 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005269 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005270 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005271 if (mute) {
5272 // FIXME: should not need to double latency if volume could be applied
5273 // immediately by the audioflinger mixer. We must account for the delay
5274 // between now and the next time the audioflinger thread for this output
5275 // will process a buffer (which corresponds to one buffer size,
5276 // usually 1/2 or 1/4 of the latency).
5277 if (muteWaitMs < desc->latency() * 2) {
5278 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005279 }
5280 }
5281 }
5282 }
5283 }
5284 }
5285
Eric Laurent99401132014-05-07 19:48:15 -07005286 // temporary mute output if device selection changes to avoid volume bursts due to
5287 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005288 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005289 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5290 // temporary mute duration is conservatively set to 4 times the reported latency
5291 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5292 if (muteWaitMs < tempMuteWaitMs) {
5293 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005294 }
Eric Laurentdc462862016-07-19 12:29:53 -07005295
Eric Laurent99401132014-05-07 19:48:15 -07005296 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005297 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005298 // make sure that we do not start the temporary mute period too early in case of
5299 // delayed device change
5300 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005301 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005302 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005303 }
5304 }
5305 }
5306
Eric Laurente552edb2014-03-10 17:42:56 -07005307 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5308 if (muteWaitMs > delayMs) {
5309 muteWaitMs -= delayMs;
5310 usleep(muteWaitMs * 1000);
5311 return muteWaitMs;
5312 }
5313 return 0;
5314}
5315
François Gaffie11d30102018-11-02 16:09:09 +01005316uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5317 const DeviceVector &devices,
5318 bool force,
5319 int delayMs,
5320 audio_patch_handle_t *patchHandle,
5321 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005322{
François Gaffie11d30102018-11-02 16:09:09 +01005323 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005324 uint32_t muteWaitMs;
5325
5326 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005327 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5328 nullptr /* patchHandle */, requiresMuteCheck);
5329 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5330 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005331 return muteWaitMs;
5332 }
Eric Laurente552edb2014-03-10 17:42:56 -07005333
5334 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005335 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005336
François Gaffie11d30102018-11-02 16:09:09 +01005337 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5338 // output profile
5339 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5340 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5341 return 0;
5342 }
Eric Laurente552edb2014-03-10 17:42:56 -07005343
François Gaffie11d30102018-11-02 16:09:09 +01005344 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005345
François Gaffie11d30102018-11-02 16:09:09 +01005346 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5347
5348 if (!filteredDevices.isEmpty()) {
5349 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005350 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005351
5352 // if the outputs are not materially active, there is no need to mute.
5353 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005354 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005355 } else {
5356 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5357 muteWaitMs = 0;
5358 }
Eric Laurente552edb2014-03-10 17:42:56 -07005359
5360 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005361 // the requested device is AUDIO_DEVICE_NONE
5362 // OR the requested device is the same as current device
5363 // AND force is not specified
5364 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005365 // Doing this check here allows the caller to call setOutputDevices() without conditions
5366 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5367 !force && outputDesc->getPatchHandle() != 0) {
5368 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5369 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005370 return muteWaitMs;
5371 }
5372
François Gaffie11d30102018-11-02 16:09:09 +01005373 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005374
Eric Laurente552edb2014-03-10 17:42:56 -07005375 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005376 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005377 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005378 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005379 PatchBuilder patchBuilder;
5380 patchBuilder.addSource(outputDesc);
5381 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5382 for (const auto &filteredDevice : filteredDevices) {
5383 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005384 }
5385
François Gaffie11d30102018-11-02 16:09:09 +01005386 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005387 }
Eric Laurente552edb2014-03-10 17:42:56 -07005388
5389 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005390 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005391
5392 return muteWaitMs;
5393}
5394
Eric Laurentc75307b2015-03-17 15:29:32 -07005395status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005396 int delayMs,
5397 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005398{
Eric Laurent6a94d692014-05-20 11:18:06 -07005399 ssize_t index;
5400 if (patchHandle) {
5401 index = mAudioPatches.indexOfKey(*patchHandle);
5402 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005403 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 }
5405 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005406 return INVALID_OPERATION;
5407 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5409 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005410 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005411 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005412 removeAudioPatch(patchDesc->mHandle);
5413 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005414 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005415 return status;
5416}
5417
5418status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005419 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 bool force,
5421 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005422{
5423 status_t status = NO_ERROR;
5424
Eric Laurent1f2f2232014-06-02 12:01:23 -07005425 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005426 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5427 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005428
François Gaffie11d30102018-11-02 16:09:09 +01005429 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005430 PatchBuilder patchBuilder;
5431 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005432 // AUDIO_SOURCE_HOTWORD is for internal use only:
5433 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005434 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5435 auto result = usecase;
5436 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5437 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5438 }
5439 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005440 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005441 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005442 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005443 }
5444 }
5445 return status;
5446}
5447
Eric Laurent6a94d692014-05-20 11:18:06 -07005448status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5449 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005450{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005451 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005452 ssize_t index;
5453 if (patchHandle) {
5454 index = mAudioPatches.indexOfKey(*patchHandle);
5455 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005456 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 }
5458 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005459 return INVALID_OPERATION;
5460 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5462 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005463 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005464 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 removeAudioPatch(patchDesc->mHandle);
5466 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005467 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005468 return status;
5469}
5470
François Gaffie11d30102018-11-02 16:09:09 +01005471sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005472 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005473 audio_format_t& format,
5474 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005475 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005476{
5477 // Choose an input profile based on the requested capture parameters: select the first available
5478 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005479 //
5480 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5481 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005482
Glenn Kasten730b9262018-03-29 15:01:26 -07005483 sp<IOProfile> firstInexact;
5484 uint32_t updatedSamplingRate = 0;
5485 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5486 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005487 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005488 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005489 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005490 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005491 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005492 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005493 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005494 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005495 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005496 &channelMask /*updatedChannelMask*/,
5497 // FIXME ugly cast
5498 (audio_output_flags_t) flags,
5499 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005500 return profile;
5501 }
François Gaffie11d30102018-11-02 16:09:09 +01005502 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005503 samplingRate,
5504 &updatedSamplingRate,
5505 format,
5506 &updatedFormat,
5507 channelMask,
5508 &updatedChannelMask,
5509 // FIXME ugly cast
5510 (audio_output_flags_t) flags,
5511 false /*exactMatchRequiredForInputFlags*/)) {
5512 firstInexact = profile;
5513 }
5514
Eric Laurente552edb2014-03-10 17:42:56 -07005515 }
5516 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005517 if (firstInexact != nullptr) {
5518 samplingRate = updatedSamplingRate;
5519 format = updatedFormat;
5520 channelMask = updatedChannelMask;
5521 return firstInexact;
5522 }
Eric Laurente552edb2014-03-10 17:42:56 -07005523 return NULL;
5524}
5525
Francois Gaffie716e1432019-01-14 16:58:59 +01005526sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5527 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005528{
Eric Laurent97ac8712018-07-27 18:59:02 -07005529 // Honor explicit routing requests only if all active clients have a preferred route in which
5530 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005531 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005532 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005533 if (device != nullptr) {
5534 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005535 }
5536
François Gaffie11d30102018-11-02 16:09:09 +01005537 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005538 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005539 policyMix);
5540 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005541 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005542}
5543
Francois Gaffie716e1432019-01-14 16:58:59 +01005544sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005545{
Francois Gaffie716e1432019-01-14 16:58:59 +01005546 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5547 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5548 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5549 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005550 String8(attributes.tags + strlen("addr=")),
5551 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005552 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005553 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005554}
5555
Eric Laurente0720872014-03-11 09:30:41 -07005556float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005557 int index,
5558 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005559{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005560 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005561
5562 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5563 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5564 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5565 // the ringtone volume
5566 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5567 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5568 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5569 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5570 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5571 }
5572
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005573 // in-call: always cap volume by voice volume + some low headroom
5574 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005575 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005576 switch (stream) {
5577 case AUDIO_STREAM_SYSTEM:
5578 case AUDIO_STREAM_RING:
5579 case AUDIO_STREAM_MUSIC:
5580 case AUDIO_STREAM_ALARM:
5581 case AUDIO_STREAM_NOTIFICATION:
5582 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5583 case AUDIO_STREAM_DTMF:
5584 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005585 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005586 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005587 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005588 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005589 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005590 if (volumeDB > maxVoiceVolDb) {
5591 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5592 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5593 volumeDB = maxVoiceVolDb;
5594 }
5595 } break;
5596 default:
5597 break;
5598 }
5599 }
5600
Eric Laurente552edb2014-03-10 17:42:56 -07005601 // if a headset is connected, apply the following rules to ring tones and notifications
5602 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005603 // - always attenuate notifications volume by 6dB
5604 // - attenuate ring tones volume by 6dB unless music is not playing and
5605 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005606 // - if music is playing, always limit the volume to current music volume,
5607 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005608 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005609 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5610 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5611 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005612 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005613 AUDIO_DEVICE_OUT_USB_HEADSET |
5614 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005615 ((stream_strategy == STRATEGY_SONIFICATION)
5616 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005617 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005618 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005619 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005620 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005621 // when the phone is ringing we must consider that music could have been paused just before
5622 // by the music application and behave as if music was active if the last music track was
5623 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005624 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005625 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005626 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005627 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005628 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005629 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5630 musicDevice),
5631 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005632 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5633 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005634 if (volumeDB > minVolDB) {
5635 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005636 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005637 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005638 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5639 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5640 // on A2DP, also ensure notification volume is not too low compared to media when
5641 // intended to be played
5642 if ((volumeDB > -96.0f) &&
5643 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5644 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5645 stream, device,
5646 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5647 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5648 }
5649 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005650 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5651 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005652 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005653 }
5654 }
5655
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005656 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005657}
5658
Eric Laurent3839bc02018-07-10 18:33:34 -07005659int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5660 audio_stream_type_t srcStream,
5661 audio_stream_type_t dstStream)
5662{
5663 if (srcStream == dstStream) {
5664 return srcIndex;
5665 }
5666 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5667 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5668 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5669 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5670
5671 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5672}
5673
Eric Laurente0720872014-03-11 09:30:41 -07005674status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005675 int index,
5676 const sp<AudioOutputDescriptor>& outputDesc,
5677 audio_devices_t device,
5678 int delayMs,
5679 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005680{
Eric Laurente552edb2014-03-10 17:42:56 -07005681 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005682 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005683 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005684 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005685 return NO_ERROR;
5686 }
François Gaffie2110e042015-03-24 08:41:51 +01005687 audio_policy_forced_cfg_t forceUseForComm =
5688 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005689 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005690 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5691 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005692 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005693 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005694 return INVALID_OPERATION;
5695 }
5696
Eric Laurentc75307b2015-03-17 15:29:32 -07005697 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005698 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005699 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005700
Eric Laurentffbc80f2015-03-18 18:30:19 -07005701 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005702 if (outputDesc->isFixedVolume(device) ||
5703 // Force VoIP volume to max for bluetooth SCO
5704 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5705 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005706 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005707 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005708
Eric Laurentffbc80f2015-03-18 18:30:19 -07005709 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005710
Eric Laurent3b73df72014-03-11 09:06:29 -07005711 if (stream == AUDIO_STREAM_VOICE_CALL ||
5712 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005713 float voiceVolume;
5714 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005715 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005716 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005717 } else {
5718 voiceVolume = 1.0;
5719 }
5720
Eric Laurent18fba842016-03-31 14:41:26 -07005721 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005722 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5723 mLastVoiceVolume = voiceVolume;
5724 }
5725 }
5726
5727 return NO_ERROR;
5728}
5729
Eric Laurentc75307b2015-03-17 15:29:32 -07005730void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5731 audio_devices_t device,
5732 int delayMs,
5733 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005734{
Eric Laurentc75307b2015-03-17 15:29:32 -07005735 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005736
Eric Laurent794fde22016-03-11 09:50:45 -08005737 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005738 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005739 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005740 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005741 device,
5742 delayMs,
5743 force);
5744 }
5745}
5746
Eric Laurente0720872014-03-11 09:30:41 -07005747void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005748 bool on,
5749 const sp<AudioOutputDescriptor>& outputDesc,
5750 int delayMs,
5751 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005752{
Eric Laurent72249d52015-06-08 11:12:15 -07005753 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5754 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005755 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005756 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005757 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005758 }
5759 }
5760}
5761
Eric Laurente0720872014-03-11 09:30:41 -07005762void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005763 bool on,
5764 const sp<AudioOutputDescriptor>& outputDesc,
5765 int delayMs,
5766 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005767{
Eric Laurente552edb2014-03-10 17:42:56 -07005768 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005769 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005770 }
5771
Eric Laurentc75307b2015-03-17 15:29:32 -07005772 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5773 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005774
5775 if (on) {
5776 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005777 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005778 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005779 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005780 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005781 }
5782 }
5783 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5784 outputDesc->mMuteCount[stream]++;
5785 } else {
5786 if (outputDesc->mMuteCount[stream] == 0) {
5787 ALOGV("setStreamMute() unmuting non muted stream!");
5788 return;
5789 }
5790 if (--outputDesc->mMuteCount[stream] == 0) {
5791 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005792 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005793 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005794 device,
5795 delayMs);
5796 }
5797 }
5798}
5799
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005800audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5801{
5802 // flags to stream type mapping
5803 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5804 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5805 }
5806 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5807 return AUDIO_STREAM_BLUETOOTH_SCO;
5808 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005809 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5810 return AUDIO_STREAM_TTS;
5811 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005812
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005813 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005814}
Eric Laurente83b55d2014-11-14 10:06:21 -08005815
François Gaffie53615e22015-03-19 09:24:12 +01005816bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5817{
Eric Laurente83b55d2014-11-14 10:06:21 -08005818 // has flags that map to a strategy?
5819 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5820 return true;
5821 }
5822
5823 // has known usage?
5824 switch (paa->usage) {
5825 case AUDIO_USAGE_UNKNOWN:
5826 case AUDIO_USAGE_MEDIA:
5827 case AUDIO_USAGE_VOICE_COMMUNICATION:
5828 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5829 case AUDIO_USAGE_ALARM:
5830 case AUDIO_USAGE_NOTIFICATION:
5831 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5832 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5833 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5834 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5835 case AUDIO_USAGE_NOTIFICATION_EVENT:
5836 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5837 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5838 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5839 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005840 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005841 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005842 break;
5843 default:
5844 return false;
5845 }
5846 return true;
5847}
5848
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005849bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005850 routing_strategy strategy, uint32_t inPastMs,
5851 nsecs_t sysTime) const
5852{
5853 if ((sysTime == 0) && (inPastMs != 0)) {
5854 sysTime = systemTime();
5855 }
Eric Laurent794fde22016-03-11 09:50:45 -08005856 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005857 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005858 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005859 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5860 return true;
5861 }
5862 }
5863 return false;
5864}
5865
François Gaffie11d30102018-11-02 16:09:09 +01005866bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5867 routing_strategy strategy, uint32_t inPastMs,
5868 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005869{
5870 for (size_t i = 0; i < mOutputs.size(); i++) {
5871 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5872 if (outputDesc->sharesHwModuleWith(desc)
5873 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5874 return true;
5875 }
5876 }
5877 return false;
5878}
5879
François Gaffie2110e042015-03-24 08:41:51 +01005880audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5881{
5882 return mEngine->getForceUse(usage);
5883}
5884
5885bool AudioPolicyManager::isInCall()
5886{
5887 return isStateInCall(mEngine->getPhoneState());
5888}
5889
5890bool AudioPolicyManager::isStateInCall(int state)
5891{
5892 return is_state_in_call(state);
5893}
5894
Eric Laurentd60560a2015-04-10 11:31:20 -07005895void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5896{
5897 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005898 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5899 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5900 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5901 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005902 }
5903 }
5904
5905 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5906 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5907 bool release = false;
5908 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5909 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5910 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5911 source->ext.device.type == deviceDesc->type()) {
5912 release = true;
5913 }
5914 }
5915 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5916 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5917 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5918 sink->ext.device.type == deviceDesc->type()) {
5919 release = true;
5920 }
5921 }
5922 if (release) {
5923 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5924 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5925 }
5926 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005927
5928 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005929}
5930
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005931void AudioPolicyManager::modifySurroundFormats(
5932 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005933 std::unordered_set<audio_format_t> enforcedSurround(
5934 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005935 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5936 for (const auto& pair : mConfig.getSurroundFormats()) {
5937 allSurround.insert(pair.first);
5938 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5939 }
Phil Burk09bc4612016-02-24 15:58:15 -08005940
5941 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5942 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005943 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005944 // This is the resulting set of formats depending on the surround mode:
5945 // 'all surround' = allSurround
5946 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5947 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5948 // 'manual surround' = mManualSurroundFormats
5949 // AUTO: formats v 'enforced surround'
5950 // ALWAYS: formats v 'all surround' v 'enforced surround'
5951 // NEVER: formats ^ 'non-surround'
5952 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005953
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005954 std::unordered_set<audio_format_t> formatSet;
5955 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5956 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005957 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005958 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005959 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005960 formatSet.insert(*formatIter);
5961 }
5962 }
5963 } else {
5964 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5965 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005966 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005967
jiabin81772902018-04-02 17:52:27 -07005968 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005969 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005970 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5971 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5972 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005973 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005974 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5975 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5976 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005977 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005978 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005979 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005980 for (const auto& format : formatSet) {
5981 formatsPtr->push(format);
5982 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005983}
5984
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005985void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005986 ChannelsVector &channelMasks = *channelMasksPtr;
5987 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5988 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5989
5990 // If NEVER, then remove support for channelMasks > stereo.
5991 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5992 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5993 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5994 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5995 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5996 channelMasks.removeAt(maskIndex);
5997 } else {
5998 maskIndex++;
5999 }
6000 }
jiabin81772902018-04-02 17:52:27 -07006001 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6002 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6003 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006004 bool supports5dot1 = false;
6005 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006006 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006007 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6008 supports5dot1 = true;
6009 break;
6010 }
6011 }
6012 // If not then add 5.1 support.
6013 if (!supports5dot1) {
6014 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006015 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006016 }
Phil Burk09bc4612016-02-24 15:58:15 -08006017 }
6018}
6019
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006020void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006021 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006022 AudioProfileVector &profiles)
6023{
6024 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006025 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006026
François Gaffie112b0af2015-11-19 16:13:25 +01006027 // Format MUST be checked first to update the list of AudioProfile
6028 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006029 reply = mpClientInterface->getParameters(
6030 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006031 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006032 AudioParameter repliedParameters(reply);
6033 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006034 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006035 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6036 return;
6037 }
Phil Burk09bc4612016-02-24 15:58:15 -08006038 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006039 if (device == AUDIO_DEVICE_OUT_HDMI
6040 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006041 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006042 }
Phil Burk09bc4612016-02-24 15:58:15 -08006043 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006044 }
François Gaffie112b0af2015-11-19 16:13:25 +01006045
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006046 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006047 ChannelsVector channelMasks;
6048 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006049 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006050 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006051
6052 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006053 reply = mpClientInterface->getParameters(
6054 ioHandle,
6055 requestedParameters.toString() + ";" +
6056 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006057 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006058 AudioParameter repliedParameters(reply);
6059 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006060 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006061 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006062 }
6063 }
6064 if (profiles.hasDynamicChannelsFor(format)) {
6065 reply = mpClientInterface->getParameters(ioHandle,
6066 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006067 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006068 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006069 AudioParameter repliedParameters(reply);
6070 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006071 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006072 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006073 if (device == AUDIO_DEVICE_OUT_HDMI
6074 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006075 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006076 }
François Gaffie112b0af2015-11-19 16:13:25 +01006077 }
6078 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006079 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006080 }
6081}
Eric Laurentd60560a2015-04-10 11:31:20 -07006082
Mikhail Naganovdc769682018-05-04 15:34:08 -07006083status_t AudioPolicyManager::installPatch(const char *caller,
6084 audio_patch_handle_t *patchHandle,
6085 AudioIODescriptorInterface *ioDescriptor,
6086 const struct audio_patch *patch,
6087 int delayMs)
6088{
6089 ssize_t index = mAudioPatches.indexOfKey(
6090 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6091 *patchHandle : ioDescriptor->getPatchHandle());
6092 sp<AudioPatch> patchDesc;
6093 status_t status = installPatch(
6094 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6095 if (status == NO_ERROR) {
6096 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6097 }
6098 return status;
6099}
6100
6101status_t AudioPolicyManager::installPatch(const char *caller,
6102 ssize_t index,
6103 audio_patch_handle_t *patchHandle,
6104 const struct audio_patch *patch,
6105 int delayMs,
6106 uid_t uid,
6107 sp<AudioPatch> *patchDescPtr)
6108{
6109 sp<AudioPatch> patchDesc;
6110 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6111 if (index >= 0) {
6112 patchDesc = mAudioPatches.valueAt(index);
6113 afPatchHandle = patchDesc->mAfPatchHandle;
6114 }
6115
6116 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6117 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6118 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6119 if (status == NO_ERROR) {
6120 if (index < 0) {
6121 patchDesc = new AudioPatch(patch, uid);
6122 addAudioPatch(patchDesc->mHandle, patchDesc);
6123 } else {
6124 patchDesc->mPatch = *patch;
6125 }
6126 patchDesc->mAfPatchHandle = afPatchHandle;
6127 if (patchHandle) {
6128 *patchHandle = patchDesc->mHandle;
6129 }
6130 nextAudioPortGeneration();
6131 mpClientInterface->onAudioPatchListUpdate();
6132 }
6133 if (patchDescPtr) *patchDescPtr = patchDesc;
6134 return status;
6135}
6136
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006137} // namespace android