blob: cf9c29829843dabbdc08804633b0fdb0c95b2770 [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);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002330 if (indexMin < 0 || indexMax < 0) {
2331 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2332 return;
2333 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01002334 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002335
2336 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002337 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2338 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002339 continue;
2340 }
2341 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002342 }
Eric Laurente552edb2014-03-10 17:42:56 -07002343}
2344
Eric Laurente0720872014-03-11 09:30:41 -07002345status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002346 int index,
2347 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002348{
2349
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002350 // VOICE_CALL and BLUETOOTH_SCO stream have minVolumeIndex > 0 but
2351 // can be muted directly by an app that has MODIFY_PHONE_STATE permission.
Nadav Bar7c605f62017-12-25 00:01:52 +02002352 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002353 !((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
2354 index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002355 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002356 return BAD_VALUE;
2357 }
2358 if (!audio_is_output_device(device)) {
2359 return BAD_VALUE;
2360 }
2361
2362 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002363 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002364
Eric Laurent1fd372e2016-04-06 14:23:53 -07002365 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002366 stream, device, index);
2367
Eric Laurent28d09f02016-03-08 10:43:05 -08002368 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002369 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2370 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002371 continue;
2372 }
2373 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2374 }
Eric Laurente552edb2014-03-10 17:42:56 -07002375
Eric Laurent1fd372e2016-04-06 14:23:53 -07002376 // update volume on all outputs and streams matching the following:
2377 // - The requested stream (or a stream matching for volume control) is active on the output
2378 // - The device (or devices) selected by the strategy corresponding to this stream includes
2379 // the requested device
2380 // - For non default requested device, currently selected device on the output is either the
2381 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002382 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2383 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002384 status_t status = NO_ERROR;
2385 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002386 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002387 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002388 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002389 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002390 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002391 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002392 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002393 continue;
2394 }
Eric Laurent794fde22016-03-11 09:50:45 -08002395 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002396 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2397 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002398 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2399 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002400 continue;
2401 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002402 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002403 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002404 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002405 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002406 } else {
2407 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002408 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002409 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002410 // rescale index before applying to curStream as ranges may be different for
2411 // stream and curStream
2412 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002413 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002414 //FIXME: workaround for truncated touch sounds
2415 // delayed volume change for system stream to be removed when the problem is
2416 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002417 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002418 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002419 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002420 if (volStatus != NO_ERROR) {
2421 status = volStatus;
2422 }
2423 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002424 }
Eric Laurente552edb2014-03-10 17:42:56 -07002425 }
2426 return status;
2427}
2428
Eric Laurente0720872014-03-11 09:30:41 -07002429status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002430 int *index,
2431 audio_devices_t device)
2432{
2433 if (index == NULL) {
2434 return BAD_VALUE;
2435 }
2436 if (!audio_is_output_device(device)) {
2437 return BAD_VALUE;
2438 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002439 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002440 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002441 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002442 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2443 }
François Gaffiedfd74092015-03-19 12:10:59 +01002444 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002445
François Gaffied1ab2bd2015-12-02 18:20:06 +01002446 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002447 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2448 return NO_ERROR;
2449}
2450
Eric Laurent36829f92017-04-07 19:04:42 -07002451audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002452{
2453 // select one output among several suitable for global effects.
2454 // The priority is as follows:
2455 // 1: An offloaded output. If the effect ends up not being offloadable,
2456 // AudioFlinger will invalidate the track and the offloaded output
2457 // will be closed causing the effect to be moved to a PCM output.
2458 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002459 // 3: The primary output
2460 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002461
Eric Laurent3b73df72014-03-11 09:06:29 -07002462 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002463 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2464 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002465
Eric Laurent36829f92017-04-07 19:04:42 -07002466 if (outputs.size() == 0) {
2467 return AUDIO_IO_HANDLE_NONE;
2468 }
Eric Laurente552edb2014-03-10 17:42:56 -07002469
Eric Laurent36829f92017-04-07 19:04:42 -07002470 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2471 bool activeOnly = true;
2472
2473 while (output == AUDIO_IO_HANDLE_NONE) {
2474 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2475 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2476 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2477
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002478 for (audio_io_handle_t output : outputs) {
2479 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002480 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2481 continue;
2482 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002483 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2484 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002485 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002486 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002487 }
2488 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002489 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002490 }
2491 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002492 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002493 }
2494 }
2495 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2496 output = outputOffloaded;
2497 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2498 output = outputDeepBuffer;
2499 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2500 output = outputPrimary;
2501 } else {
2502 output = outputs[0];
2503 }
2504 activeOnly = false;
2505 }
2506
2507 if (output != mMusicEffectOutput) {
2508 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2509 mMusicEffectOutput = output;
2510 }
2511
2512 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002513 return output;
2514}
2515
Eric Laurent36829f92017-04-07 19:04:42 -07002516audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2517{
2518 return selectOutputForMusicEffects();
2519}
2520
Eric Laurente0720872014-03-11 09:30:41 -07002521status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002522 audio_io_handle_t io,
2523 uint32_t strategy,
2524 int session,
2525 int id)
2526{
2527 ssize_t index = mOutputs.indexOfKey(io);
2528 if (index < 0) {
2529 index = mInputs.indexOfKey(io);
2530 if (index < 0) {
2531 ALOGW("registerEffect() unknown io %d", io);
2532 return INVALID_OPERATION;
2533 }
2534 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002535 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002536}
2537
Eric Laurentc241b0d2018-11-28 09:08:49 -08002538status_t AudioPolicyManager::unregisterEffect(int id)
2539{
2540 if (mEffects.getEffect(id) == nullptr) {
2541 return INVALID_OPERATION;
2542 }
2543
2544 if (mEffects.isEffectEnabled(id)) {
2545 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2546 setEffectEnabled(id, false);
2547 }
2548 return mEffects.unregisterEffect(id);
2549}
2550
2551status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2552{
2553 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2554 if (effect == nullptr) {
2555 return INVALID_OPERATION;
2556 }
2557
2558 status_t status = mEffects.setEffectEnabled(id, enabled);
2559 if (status == NO_ERROR) {
2560 mInputs.trackEffectEnabled(effect, enabled);
2561 }
2562 return status;
2563}
2564
Eric Laurentc75307b2015-03-17 15:29:32 -07002565bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2566{
Eric Laurent28d09f02016-03-08 10:43:05 -08002567 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002568 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2569 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002570 continue;
2571 }
2572 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2573 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002574 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002575}
2576
2577bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2578{
2579 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2580}
2581
Eric Laurente0720872014-03-11 09:30:41 -07002582bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002583{
2584 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002585 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002586 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002587 return true;
2588 }
2589 }
2590 return false;
2591}
2592
Eric Laurent275e8e92014-11-30 15:14:47 -08002593// Register a list of custom mixes with their attributes and format.
2594// When a mix is registered, corresponding input and output profiles are
2595// added to the remote submix hw module. The profile contains only the
2596// parameters (sampling rate, format...) specified by the mix.
2597// The corresponding input remote submix device is also connected.
2598//
2599// When a remote submix device is connected, the address is checked to select the
2600// appropriate profile and the corresponding input or output stream is opened.
2601//
2602// When capture starts, getInputForAttr() will:
2603// - 1 look for a mix matching the address passed in attribtutes tags if any
2604// - 2 if none found, getDeviceForInputSource() will:
2605// - 2.1 look for a mix matching the attributes source
2606// - 2.2 if none found, default to device selection by policy rules
2607// At this time, the corresponding output remote submix device is also connected
2608// and active playback use cases can be transferred to this mix if needed when reconnecting
2609// after AudioTracks are invalidated
2610//
2611// When playback starts, getOutputForAttr() will:
2612// - 1 look for a mix matching the address passed in attribtutes tags if any
2613// - 2 if none found, look for a mix matching the attributes usage
2614// - 3 if none found, default to device and output selection by policy rules.
2615
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002616status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002617{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002618 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2619 status_t res = NO_ERROR;
2620
2621 sp<HwModule> rSubmixModule;
2622 // examine each mix's route type
2623 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002624 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002625 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002626 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002627 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002628 break;
2629 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002630 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002631 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002633 rSubmixModule = mHwModules.getModuleFromName(
2634 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2635 if (rSubmixModule == 0) {
2636 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2637 i);
2638 res = INVALID_OPERATION;
2639 break;
2640 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002641 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002642
Eric Laurent97ac8712018-07-27 18:59:02 -07002643 String8 address = mix.mDeviceAddress;
2644 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2645 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2646 } else {
2647 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2648 }
François Gaffie036e1e92015-03-19 10:16:24 +01002649
Eric Laurent97ac8712018-07-27 18:59:02 -07002650 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002651 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002652 res = INVALID_OPERATION;
2653 break;
2654 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002655 audio_config_t outputConfig = mix.mFormat;
2656 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002657 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2658 // stereo and let audio flinger do the channel conversion if needed.
2659 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2660 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2661 rSubmixModule->addOutputProfile(address, &outputConfig,
2662 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2663 rSubmixModule->addInputProfile(address, &inputConfig,
2664 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002665
Eric Laurent97ac8712018-07-27 18:59:02 -07002666 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002667 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2668 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002669 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002670 } else {
2671 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2672 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002673 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002675 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2676 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002677 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002678 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002679 i, mixes.size(), type, address.string());
2680
2681 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2682 mix.mDeviceType, mix.mDeviceAddress,
2683 String8(), AUDIO_FORMAT_DEFAULT);
2684 if (device == nullptr) {
2685 res = INVALID_OPERATION;
2686 break;
2687 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002688
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002689 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002690 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2691 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002692
2693 if (desc->supportedDevices().contains(device)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002694 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002695 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002696 } else {
2697 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002698 }
2699 break;
2700 }
2701 }
2702
2703 if (res != NO_ERROR) {
2704 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002705 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002706 res = INVALID_OPERATION;
2707 break;
2708 } else if (!foundOutput) {
2709 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002710 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002711 res = INVALID_OPERATION;
2712 break;
2713 }
Eric Laurentc722f302014-12-10 11:21:49 -08002714 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002715 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002716 if (res != NO_ERROR) {
2717 unregisterPolicyMixes(mixes);
2718 }
2719 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002720}
2721
2722status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2723{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002724 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002725 status_t res = NO_ERROR;
2726 sp<HwModule> rSubmixModule;
2727 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002728 for (const auto& mix : mixes) {
2729 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002730
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002731 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002732 rSubmixModule = mHwModules.getModuleFromName(
2733 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2734 if (rSubmixModule == 0) {
2735 res = INVALID_OPERATION;
2736 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002737 }
2738 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002739
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002740 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002741
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002742 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2743 res = INVALID_OPERATION;
2744 continue;
2745 }
2746
2747 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2748 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2749 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2750 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002751 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002752 }
2753 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2754 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2755 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2756 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002757 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002758 }
2759 rSubmixModule->removeOutputProfile(address);
2760 rSubmixModule->removeInputProfile(address);
2761
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002762 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2763 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002764 res = INVALID_OPERATION;
2765 continue;
2766 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002767 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002768 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002769 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002770}
2771
Mikhail Naganov100f0122018-11-29 11:22:16 -08002772void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2773{
2774 size_t i = 0;
2775 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2776 for (const auto& fmt : mManualSurroundFormats) {
2777 if (i++ != 0) dst->append(", ");
2778 std::string sfmt;
2779 FormatConverter::toString(fmt, sfmt);
2780 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2781 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2782 }
2783}
2784
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002785status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2786 const Vector<AudioDeviceTypeAddr>& devices) {
2787 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2788 // uid/device affinity is only for output devices
2789 for (size_t i = 0; i < devices.size(); i++) {
2790 if (!audio_is_output_device(devices[i].mType)) {
2791 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2792 devices[i].mType);
2793 return BAD_VALUE;
2794 }
2795 }
2796 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2797 if (res == NO_ERROR) {
2798 // reevaluate outputs for all given devices
2799 for (size_t i = 0; i < devices.size(); i++) {
2800 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002801 devices[i].mType, devices[i].mAddress, String8(),
2802 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002803 SortedVector<audio_io_handle_t> outputs;
2804 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002805 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002806 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2807 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2808 return INVALID_OPERATION;
2809 }
2810 }
2811 }
2812 return res;
2813}
2814
2815status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2816 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2817 Vector<AudioDeviceTypeAddr> devices;
2818 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2819 if (res == NO_ERROR) {
2820 // reevaluate outputs for all found devices
2821 for (size_t i = 0; i < devices.size(); i++) {
2822 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002823 devices[i].mType, devices[i].mAddress, String8(),
2824 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002825 SortedVector<audio_io_handle_t> outputs;
2826 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002827 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002828 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2829 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2830 return INVALID_OPERATION;
2831 }
2832 }
2833 }
2834
2835 return res;
2836}
2837
Andy Hungc29d82b2018-10-05 12:23:17 -07002838void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002839{
Andy Hungc29d82b2018-10-05 12:23:17 -07002840 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2841 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002842 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002843 std::string stateLiteral;
2844 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002845 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002846 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2847 "communications", "media", "record", "dock", "system",
2848 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2849 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2850 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002851 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2852 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2853 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2854 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2855 dst->append(" (MANUAL: ");
2856 dumpManualSurroundFormats(dst);
2857 dst->append(")");
2858 }
2859 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002860 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002861 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2862 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2863 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2864 mAvailableOutputDevices.dump(dst, String8("Available output"));
2865 mAvailableInputDevices.dump(dst, String8("Available input"));
2866 mHwModulesAll.dump(dst);
2867 mOutputs.dump(dst);
2868 mInputs.dump(dst);
2869 mVolumeCurves->dump(dst);
2870 mEffects.dump(dst);
2871 mAudioPatches.dump(dst);
2872 mPolicyMixes.dump(dst);
2873 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002874}
2875
2876status_t AudioPolicyManager::dump(int fd)
2877{
2878 String8 result;
2879 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002880 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002881 return NO_ERROR;
2882}
2883
2884// This function checks for the parameters which can be offloaded.
2885// This can be enhanced depending on the capability of the DSP and policy
2886// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002887bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002888{
2889 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002890 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002891 offloadInfo.sample_rate, offloadInfo.channel_mask,
2892 offloadInfo.format,
2893 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2894 offloadInfo.has_video);
2895
Andy Hung2ddee192015-12-18 17:34:44 -08002896 if (mMasterMono) {
2897 return false; // no offloading if mono is set.
2898 }
2899
Eric Laurente552edb2014-03-10 17:42:56 -07002900 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002901 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2902 ALOGV("offload disabled by audio.offload.disable");
2903 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002904 }
2905
2906 // Check if stream type is music, then only allow offload as of now.
2907 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2908 {
2909 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2910 return false;
2911 }
2912
2913 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002914 const bool allowOffloadWithVideo =
2915 property_get_bool("audio.offload.video", false /* default_value */);
2916 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002917 ALOGV("isOffloadSupported: has_video == true, returning false");
2918 return false;
2919 }
2920
2921 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002922 const int min_duration_secs = property_get_int32(
2923 "audio.offload.min.duration.secs", -1 /* default_value */);
2924 if (min_duration_secs >= 0) {
2925 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2926 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2927 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002928 return false;
2929 }
2930 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2931 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2932 return false;
2933 }
2934
2935 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2936 // creating an offloaded track and tearing it down immediately after start when audioflinger
2937 // detects there is an active non offloadable effect.
2938 // FIXME: We should check the audio session here but we do not have it in this context.
2939 // This may prevent offloading in rare situations where effects are left active by apps
2940 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002941 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002942 return false;
2943 }
2944
2945 // See if there is a profile to support this.
2946 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002947 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002948 offloadInfo.sample_rate,
2949 offloadInfo.format,
2950 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002951 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2952 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002953 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2954 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002955}
2956
Michael Chana94fbb22018-04-24 14:31:19 +10002957bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2958 const audio_attributes_t& attributes) {
2959 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2960 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002961 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002962 config.sample_rate,
2963 config.format,
2964 config.channel_mask,
2965 output_flags,
2966 true /* directOnly */);
2967 ALOGV("%s() profile %sfound with name: %s, "
2968 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2969 __FUNCTION__, profile != 0 ? "" : "NOT ",
2970 (profile != 0 ? profile->getTagName().string() : "null"),
2971 config.sample_rate, config.format, config.channel_mask, output_flags);
2972 return (profile != 0);
2973}
2974
Eric Laurent6a94d692014-05-20 11:18:06 -07002975status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2976 audio_port_type_t type,
2977 unsigned int *num_ports,
2978 struct audio_port *ports,
2979 unsigned int *generation)
2980{
2981 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2982 generation == NULL) {
2983 return BAD_VALUE;
2984 }
2985 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2986 if (ports == NULL) {
2987 *num_ports = 0;
2988 }
2989
2990 size_t portsWritten = 0;
2991 size_t portsMax = *num_ports;
2992 *num_ports = 0;
2993 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002994 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2995 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002997 for (const auto& dev : mAvailableOutputDevices) {
2998 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002999 continue;
3000 }
3001 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003002 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003003 }
3004 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 }
3007 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003008 for (const auto& dev : mAvailableInputDevices) {
3009 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003010 continue;
3011 }
3012 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003013 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003014 }
3015 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003016 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 }
3018 }
3019 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3020 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3021 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3022 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3023 }
3024 *num_ports += mInputs.size();
3025 }
3026 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003027 size_t numOutputs = 0;
3028 for (size_t i = 0; i < mOutputs.size(); i++) {
3029 if (!mOutputs[i]->isDuplicated()) {
3030 numOutputs++;
3031 if (portsWritten < portsMax) {
3032 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3033 }
3034 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003035 }
Eric Laurent84c70242014-06-23 08:46:27 -07003036 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003037 }
3038 }
3039 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003040 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003041 return NO_ERROR;
3042}
3043
Eric Laurent99fcae42018-05-17 16:59:18 -07003044status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003045{
Eric Laurent99fcae42018-05-17 16:59:18 -07003046 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3047 return BAD_VALUE;
3048 }
3049 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3050 if (dev != 0) {
3051 dev->toAudioPort(port);
3052 return NO_ERROR;
3053 }
3054 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3055 if (dev != 0) {
3056 dev->toAudioPort(port);
3057 return NO_ERROR;
3058 }
3059 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3060 if (out != 0) {
3061 out->toAudioPort(port);
3062 return NO_ERROR;
3063 }
3064 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3065 if (in != 0) {
3066 in->toAudioPort(port);
3067 return NO_ERROR;
3068 }
3069 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003070}
3071
Eric Laurent6a94d692014-05-20 11:18:06 -07003072status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3073 audio_patch_handle_t *handle,
3074 uid_t uid)
3075{
3076 ALOGV("createAudioPatch()");
3077
3078 if (handle == NULL || patch == NULL) {
3079 return BAD_VALUE;
3080 }
3081 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3082
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003083 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003084 return BAD_VALUE;
3085 }
3086 // only one source per audio patch supported for now
3087 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003088 return INVALID_OPERATION;
3089 }
Eric Laurent874c42872014-08-08 15:13:39 -07003090
3091 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 return INVALID_OPERATION;
3093 }
Eric Laurent874c42872014-08-08 15:13:39 -07003094 for (size_t i = 0; i < patch->num_sinks; i++) {
3095 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3096 return INVALID_OPERATION;
3097 }
3098 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003099
3100 sp<AudioPatch> patchDesc;
3101 ssize_t index = mAudioPatches.indexOfKey(*handle);
3102
Eric Laurent6a94d692014-05-20 11:18:06 -07003103 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3104 patch->sources[0].role,
3105 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003106#if LOG_NDEBUG == 0
3107 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003108 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003109 patch->sinks[i].role,
3110 patch->sinks[i].type);
3111 }
3112#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003113
3114 if (index >= 0) {
3115 patchDesc = mAudioPatches.valueAt(index);
3116 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3117 mUidCached, patchDesc->mUid, uid);
3118 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3119 return INVALID_OPERATION;
3120 }
3121 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003122 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 }
3124
3125 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003126 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003127 if (outputDesc == NULL) {
3128 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3129 return BAD_VALUE;
3130 }
Eric Laurent84c70242014-06-23 08:46:27 -07003131 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3132 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003133 if (patchDesc != 0) {
3134 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3135 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3136 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3137 return BAD_VALUE;
3138 }
3139 }
Eric Laurent874c42872014-08-08 15:13:39 -07003140 DeviceVector devices;
3141 for (size_t i = 0; i < patch->num_sinks; i++) {
3142 // Only support mix to devices connection
3143 // TODO add support for mix to mix connection
3144 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3145 ALOGV("createAudioPatch() source mix but sink is not a device");
3146 return INVALID_OPERATION;
3147 }
3148 sp<DeviceDescriptor> devDesc =
3149 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3150 if (devDesc == 0) {
3151 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3152 return BAD_VALUE;
3153 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003154
François Gaffie11d30102018-11-02 16:09:09 +01003155 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003156 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003157 NULL, // updatedSamplingRate
3158 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003159 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003160 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003161 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003162 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003163 ALOGV("createAudioPatch() profile not supported for device %08x",
3164 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003165 return INVALID_OPERATION;
3166 }
3167 devices.add(devDesc);
3168 }
3169 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 return INVALID_OPERATION;
3171 }
Eric Laurent874c42872014-08-08 15:13:39 -07003172
Eric Laurent6a94d692014-05-20 11:18:06 -07003173 // TODO: reconfigure output format and channels here
3174 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003175 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003176 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 index = mAudioPatches.indexOfKey(*handle);
3178 if (index >= 0) {
3179 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3180 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3181 }
3182 patchDesc = mAudioPatches.valueAt(index);
3183 patchDesc->mUid = uid;
3184 ALOGV("createAudioPatch() success");
3185 } else {
3186 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3187 return INVALID_OPERATION;
3188 }
3189 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3190 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3191 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003192 // only one sink supported when connecting an input device to a mix
3193 if (patch->num_sinks > 1) {
3194 return INVALID_OPERATION;
3195 }
François Gaffie53615e22015-03-19 09:24:12 +01003196 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 if (inputDesc == NULL) {
3198 return BAD_VALUE;
3199 }
3200 if (patchDesc != 0) {
3201 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3202 return BAD_VALUE;
3203 }
3204 }
François Gaffie11d30102018-11-02 16:09:09 +01003205 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003206 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003207 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003208 return BAD_VALUE;
3209 }
3210
François Gaffie11d30102018-11-02 16:09:09 +01003211 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003212 patch->sinks[0].sample_rate,
3213 NULL, /*updatedSampleRate*/
3214 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003215 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003216 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003217 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003218 // FIXME for the parameter type,
3219 // and the NONE
3220 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003221 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003222 return INVALID_OPERATION;
3223 }
3224 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003225 ALOGV("%s() setting device %s on output %d", __func__,
3226 device->toString().c_str(), inputDesc->mIoHandle);
3227 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003228 index = mAudioPatches.indexOfKey(*handle);
3229 if (index >= 0) {
3230 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3231 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3232 }
3233 patchDesc = mAudioPatches.valueAt(index);
3234 patchDesc->mUid = uid;
3235 ALOGV("createAudioPatch() success");
3236 } else {
3237 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3238 return INVALID_OPERATION;
3239 }
3240 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3241 // device to device connection
3242 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003243 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003244 return BAD_VALUE;
3245 }
3246 }
François Gaffie11d30102018-11-02 16:09:09 +01003247 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003248 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003249 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003250 return BAD_VALUE;
3251 }
Eric Laurent874c42872014-08-08 15:13:39 -07003252
Eric Laurent6a94d692014-05-20 11:18:06 -07003253 //update source and sink with our own data as the data passed in the patch may
3254 // be incomplete.
3255 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003256 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003257
Eric Laurent874c42872014-08-08 15:13:39 -07003258 for (size_t i = 0; i < patch->num_sinks; i++) {
3259 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3260 ALOGV("createAudioPatch() source device but one sink is not a device");
3261 return INVALID_OPERATION;
3262 }
3263
François Gaffie11d30102018-11-02 16:09:09 +01003264 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003265 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003266 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003267 return BAD_VALUE;
3268 }
François Gaffie11d30102018-11-02 16:09:09 +01003269 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003270
Eric Laurent3bcf8592015-04-03 12:13:24 -07003271 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003272 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003273 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003274 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003275 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3276 (srcDevice->getModuleVersionMajor() < 3) ||
3277 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003278 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003279 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003280 return INVALID_OPERATION;
3281 }
Eric Laurent874c42872014-08-08 15:13:39 -07003282 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003283 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003284 // if the sink device is reachable via an opened output stream, request to go via
3285 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003286 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003287 if (output != AUDIO_IO_HANDLE_NONE) {
3288 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3289 if (outputDesc->isDuplicated()) {
3290 return INVALID_OPERATION;
3291 }
3292 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003293 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003294 newPatch.num_sources = 2;
3295 }
Eric Laurent83b88082014-06-20 18:31:16 -07003296 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003297 }
3298 // TODO: check from routing capabilities in config file and other conflicting patches
3299
Mikhail Naganovdc769682018-05-04 15:34:08 -07003300 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3301 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003302 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3303 status);
3304 return INVALID_OPERATION;
3305 }
3306 } else {
3307 return BAD_VALUE;
3308 }
3309 } else {
3310 return BAD_VALUE;
3311 }
3312 return NO_ERROR;
3313}
3314
3315status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3316 uid_t uid)
3317{
3318 ALOGV("releaseAudioPatch() patch %d", handle);
3319
3320 ssize_t index = mAudioPatches.indexOfKey(handle);
3321
3322 if (index < 0) {
3323 return BAD_VALUE;
3324 }
3325 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3326 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3327 mUidCached, patchDesc->mUid, uid);
3328 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3329 return INVALID_OPERATION;
3330 }
3331
3332 struct audio_patch *patch = &patchDesc->mPatch;
3333 patchDesc->mUid = mUidCached;
3334 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003335 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003336 if (outputDesc == NULL) {
3337 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3338 return BAD_VALUE;
3339 }
3340
François Gaffie11d30102018-11-02 16:09:09 +01003341 setOutputDevices(outputDesc,
3342 getNewOutputDevices(outputDesc, true /*fromCache*/),
3343 true,
3344 0,
3345 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003346 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3347 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003348 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003349 if (inputDesc == NULL) {
3350 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3351 return BAD_VALUE;
3352 }
3353 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003354 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003355 true,
3356 NULL);
3357 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003358 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3359 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3360 status, patchDesc->mAfPatchHandle);
3361 removeAudioPatch(patchDesc->mHandle);
3362 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003363 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003364 } else {
3365 return BAD_VALUE;
3366 }
3367 } else {
3368 return BAD_VALUE;
3369 }
3370 return NO_ERROR;
3371}
3372
3373status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3374 struct audio_patch *patches,
3375 unsigned int *generation)
3376{
François Gaffie53615e22015-03-19 09:24:12 +01003377 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003378 return BAD_VALUE;
3379 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003380 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003381 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003382}
3383
Eric Laurente1715a42014-05-20 11:30:42 -07003384status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003385{
Eric Laurente1715a42014-05-20 11:30:42 -07003386 ALOGV("setAudioPortConfig()");
3387
3388 if (config == NULL) {
3389 return BAD_VALUE;
3390 }
3391 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3392 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003393 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3394 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003395 }
3396
Eric Laurenta121f902014-06-03 13:32:54 -07003397 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003398 if (config->type == AUDIO_PORT_TYPE_MIX) {
3399 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003400 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003401 if (outputDesc == NULL) {
3402 return BAD_VALUE;
3403 }
Eric Laurent84c70242014-06-23 08:46:27 -07003404 ALOG_ASSERT(!outputDesc->isDuplicated(),
3405 "setAudioPortConfig() called on duplicated output %d",
3406 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003407 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003408 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003409 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003410 if (inputDesc == NULL) {
3411 return BAD_VALUE;
3412 }
Eric Laurenta121f902014-06-03 13:32:54 -07003413 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003414 } else {
3415 return BAD_VALUE;
3416 }
3417 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3418 sp<DeviceDescriptor> deviceDesc;
3419 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3420 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3421 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3422 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3423 } else {
3424 return BAD_VALUE;
3425 }
3426 if (deviceDesc == NULL) {
3427 return BAD_VALUE;
3428 }
Eric Laurenta121f902014-06-03 13:32:54 -07003429 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003430 } else {
3431 return BAD_VALUE;
3432 }
3433
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003434 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003435 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3436 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003437 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003438 audioPortConfig->toAudioPortConfig(&newConfig, config);
3439 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003440 }
Eric Laurenta121f902014-06-03 13:32:54 -07003441 if (status != NO_ERROR) {
3442 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003443 }
Eric Laurente1715a42014-05-20 11:30:42 -07003444
3445 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003446}
3447
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003448void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3449{
Eric Laurentd60560a2015-04-10 11:31:20 -07003450 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003451 clearAudioPatches(uid);
3452 clearSessionRoutes(uid);
3453}
3454
Eric Laurent6a94d692014-05-20 11:18:06 -07003455void AudioPolicyManager::clearAudioPatches(uid_t uid)
3456{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003457 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003458 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3459 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003460 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003461 }
3462 }
3463}
3464
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003465void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3466 audio_io_handle_t ouptutToSkip)
3467{
François Gaffie11d30102018-11-02 16:09:09 +01003468 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3469 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003470 for (size_t j = 0; j < mOutputs.size(); j++) {
3471 if (mOutputs.keyAt(j) == ouptutToSkip) {
3472 continue;
3473 }
3474 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3475 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3476 continue;
3477 }
3478 // If the default device for this strategy is on another output mix,
3479 // invalidate all tracks in this strategy to force re connection.
3480 // Otherwise select new device on the output mix.
3481 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003482 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003483 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3484 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3485 }
3486 }
3487 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003488 setOutputDevices(
3489 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003490 }
3491 }
3492}
3493
3494void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3495{
3496 // remove output routes associated with this uid
3497 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003498 for (size_t i = 0; i < mOutputs.size(); i++) {
3499 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003500 for (const auto& client : outputDesc->getClientIterable()) {
3501 if (client->hasPreferredDevice() && client->uid() == uid) {
3502 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3503 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003504 }
3505 }
3506 }
3507 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003508 for (const auto& strategy : affectedStrategies) {
3509 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003510 }
3511
3512 // remove input routes associated with this uid
3513 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003514 for (size_t i = 0; i < mInputs.size(); i++) {
3515 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003516 for (const auto& client : inputDesc->getClientIterable()) {
3517 if (client->hasPreferredDevice() && client->uid() == uid) {
3518 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3519 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003520 }
3521 }
3522 }
3523 // reroute inputs if necessary
3524 SortedVector<audio_io_handle_t> inputsToClose;
3525 for (size_t i = 0; i < mInputs.size(); i++) {
3526 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003527 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003528 inputsToClose.add(inputDesc->mIoHandle);
3529 }
3530 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003531 for (const auto& input : inputsToClose) {
3532 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003533 }
3534}
3535
Eric Laurentd60560a2015-04-10 11:31:20 -07003536void AudioPolicyManager::clearAudioSources(uid_t uid)
3537{
3538 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003539 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3540 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003541 stopAudioSource(mAudioSources.keyAt(i));
3542 }
3543 }
3544}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003545
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003546status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3547 audio_io_handle_t *ioHandle,
3548 audio_devices_t *device)
3549{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003550 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3551 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003552 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3553 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003554
François Gaffiedf372692015-03-19 10:43:27 +01003555 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003556}
3557
Eric Laurentd60560a2015-04-10 11:31:20 -07003558status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003559 const audio_attributes_t *attributes,
3560 audio_port_handle_t *portId,
3561 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003562{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003563 ALOGV("%s", __FUNCTION__);
3564 *portId = AUDIO_PORT_HANDLE_NONE;
3565
3566 if (source == NULL || attributes == NULL || portId == NULL) {
3567 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3568 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003569 return BAD_VALUE;
3570 }
3571
Eric Laurentd60560a2015-04-10 11:31:20 -07003572 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3573 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003574 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3575 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003576 return INVALID_OPERATION;
3577 }
3578
François Gaffie11d30102018-11-02 16:09:09 +01003579 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003580 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003581 String8(source->ext.device.address),
3582 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003583 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003584 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003585 return BAD_VALUE;
3586 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003587
3588 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003589
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003590 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003591 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003592
3593 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003594 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003595 streamTypefromAttributesInt(attributes),
3596 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003597
3598 status_t status = connectAudioSource(sourceDesc);
3599 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003600 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003601 }
3602 return status;
3603}
3604
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003605status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003606{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003607 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003608
3609 // make sure we only have one patch per source.
3610 disconnectAudioSource(sourceDesc);
3611
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003612 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003613 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003614 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003615 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003616
François Gaffie11d30102018-11-02 16:09:09 +01003617 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3618 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3619 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3620 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3621 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003622
3623 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003624
François Gaffie11d30102018-11-02 16:09:09 +01003625 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3626 srcDevice->getModuleVersionMajor() >= 3 &&
3627 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3628 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003629 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003630 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003631 // create patch between src device and output device
3632 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003633 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003634 audio_attributes_t resultAttr;
3635 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3636 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3637 config.sample_rate = sourceDesc->config().sample_rate;
3638 config.channel_mask = sourceDesc->config().channel_mask;
3639 config.format = sourceDesc->config().format;
3640 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3641 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3642 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3643 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003644 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003645 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003646 return INVALID_OPERATION;
3647 }
3648 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3649 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003650 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003651 return INVALID_OPERATION;
3652 }
Eric Laurent733ce942017-12-07 12:18:25 -08003653 status_t status = outputDesc->start();
3654 if (status != NO_ERROR) {
3655 return status;
3656 }
3657
Eric Laurentd60560a2015-04-10 11:31:20 -07003658 // create a special patch with no sink and two sources:
3659 // - the second source indicates to PatchPanel through which output mix this patch should
3660 // be connected as well as the stream type for volume control
3661 // - the sink is defined by whatever output device is currently selected for the output
3662 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003663 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003664 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003665 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003666 &afPatchHandle,
3667 0);
3668 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3669 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003670 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003671 if (status != NO_ERROR) {
3672 ALOGW("%s patch panel could not connect device patch, error %d",
3673 __FUNCTION__, status);
3674 return INVALID_OPERATION;
3675 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003676
3677 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3678 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3679 return INVALID_OPERATION;
3680 }
3681 outputDesc->addClient(sourceDesc);
3682
Eric Laurentd60560a2015-04-10 11:31:20 -07003683 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003684 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003685
3686 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003687 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003688 return status;
3689 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003690 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003691 if (delayMs != 0) {
3692 usleep(delayMs * 1000);
3693 }
3694 }
3695
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003696 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3697 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003698
3699 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003700}
3701
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003702status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003703{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003704 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3705 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003706 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003707 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003708 return BAD_VALUE;
3709 }
3710 status_t status = disconnectAudioSource(sourceDesc);
3711
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003712 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003713 return status;
3714}
3715
Andy Hung2ddee192015-12-18 17:34:44 -08003716status_t AudioPolicyManager::setMasterMono(bool mono)
3717{
3718 if (mMasterMono == mono) {
3719 return NO_ERROR;
3720 }
3721 mMasterMono = mono;
3722 // if enabling mono we close all offloaded devices, which will invalidate the
3723 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3724 // for recreating the new AudioTrack as non-offloaded PCM.
3725 //
3726 // If disabling mono, we leave all tracks as is: we don't know which clients
3727 // and tracks are able to be recreated as offloaded. The next "song" should
3728 // play back offloaded.
3729 if (mMasterMono) {
3730 Vector<audio_io_handle_t> offloaded;
3731 for (size_t i = 0; i < mOutputs.size(); ++i) {
3732 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3733 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3734 offloaded.push(desc->mIoHandle);
3735 }
3736 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003737 for (const auto& handle : offloaded) {
3738 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003739 }
3740 }
3741 // update master mono for all remaining outputs
3742 for (size_t i = 0; i < mOutputs.size(); ++i) {
3743 updateMono(mOutputs.keyAt(i));
3744 }
3745 return NO_ERROR;
3746}
3747
3748status_t AudioPolicyManager::getMasterMono(bool *mono)
3749{
3750 *mono = mMasterMono;
3751 return NO_ERROR;
3752}
3753
Eric Laurentac9cef52017-06-09 15:46:26 -07003754float AudioPolicyManager::getStreamVolumeDB(
3755 audio_stream_type_t stream, int index, audio_devices_t device)
3756{
3757 return computeVolume(stream, index, device);
3758}
3759
jiabin81772902018-04-02 17:52:27 -07003760status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3761 audio_format_t *surroundFormats,
3762 bool *surroundFormatsEnabled,
3763 bool reported)
3764{
3765 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3766 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3767 return BAD_VALUE;
3768 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003769 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3770 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003771
3772 size_t formatsWritten = 0;
3773 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003774 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003775 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003776 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003777 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003778 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3779 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3780 FormatVector supportedFormats =
3781 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3782 for (size_t j = 0; j < supportedFormats.size(); j++) {
3783 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3784 formats.insert(supportedFormats[j]);
3785 } else {
3786 for (const auto& pair : mConfig.getSurroundFormats()) {
3787 if (pair.second.count(supportedFormats[j]) != 0) {
3788 formats.insert(pair.first);
3789 break;
3790 }
3791 }
3792 }
3793 }
jiabin81772902018-04-02 17:52:27 -07003794 }
3795 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003796 for (const auto& pair : mConfig.getSurroundFormats()) {
3797 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003798 }
3799 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003800 *numSurroundFormats = formats.size();
3801 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3802 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003803 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003804 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003805 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003806 bool formatEnabled = true;
3807 switch (forceUse) {
3808 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3809 formatEnabled = mManualSurroundFormats.count(format) != 0;
3810 break;
3811 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3812 formatEnabled = false;
3813 break;
3814 default: // AUTO or ALWAYS => true
3815 break;
jiabin81772902018-04-02 17:52:27 -07003816 }
3817 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3818 }
jiabin81772902018-04-02 17:52:27 -07003819 }
3820 return NO_ERROR;
3821}
3822
3823status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3824{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003825 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003826 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3827 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003828 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003829 return BAD_VALUE;
3830 }
3831
Mikhail Naganov100f0122018-11-29 11:22:16 -08003832 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3833 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003834 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003835 return INVALID_OPERATION;
3836 }
3837
Mikhail Naganov100f0122018-11-29 11:22:16 -08003838 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003839 return NO_ERROR;
3840 }
3841
Mikhail Naganov100f0122018-11-29 11:22:16 -08003842 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003843 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003844 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003845 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003846 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003847 }
3848 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003849 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003850 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003851 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003852 }
3853 }
3854
3855 sp<SwAudioOutputDescriptor> outputDesc;
3856 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003857 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003858 AUDIO_DEVICE_OUT_HDMI);
3859 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3860 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003861 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003862 String8 name = hdmiOutputDevices[i]->getName();
3863 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3864 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3865 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003866 name.c_str(),
3867 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003868 if (status != NO_ERROR) {
3869 continue;
3870 }
3871 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3872 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3873 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003874 name.c_str(),
3875 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003876 profileUpdated |= (status == NO_ERROR);
3877 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003878 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003879 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003880 AUDIO_DEVICE_IN_HDMI);
3881 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3882 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003883 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003884 String8 name = hdmiInputDevices[i]->getName();
3885 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3886 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3887 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003888 name.c_str(),
3889 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003890 if (status != NO_ERROR) {
3891 continue;
3892 }
3893 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3894 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3895 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003896 name.c_str(),
3897 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003898 profileUpdated |= (status == NO_ERROR);
3899 }
3900
jiabin81772902018-04-02 17:52:27 -07003901 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003902 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003903 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003904 }
3905
3906 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3907}
3908
Eric Laurentf32108e2018-10-04 17:22:04 -07003909void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003910{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003911 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003912
Eric Laurenta9f86652018-11-28 17:23:11 -08003913 for (size_t i = 0; i < mInputs.size(); i++) {
3914 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3915 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003916 for (const auto& client : clients) {
3917 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003918 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003919 }
3920 }
3921 }
3922}
3923
jiabin6012f912018-11-02 17:06:30 -07003924bool AudioPolicyManager::isHapticPlaybackSupported()
3925{
3926 for (const auto& hwModule : mHwModules) {
3927 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3928 for (const auto &outProfile : outputProfiles) {
3929 struct audio_port audioPort;
3930 outProfile->toAudioPort(&audioPort);
3931 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3932 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3933 return true;
3934 }
3935 }
3936 }
3937 }
3938 return false;
3939}
3940
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003941status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003942{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003943 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003944
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003945 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003946 if (patchDesc == 0) {
3947 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003948 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003949 return BAD_VALUE;
3950 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003951 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003952
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003953 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003954 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003955 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003956 if (status == NO_ERROR) {
3957 swOutputDesc->stop();
3958 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003959 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3960 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003961 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003962 if (hwOutputDesc != 0) {
3963 // release patch between src device and output device
3964 // close Hwoutput and remove from mHwOutputs
3965 } else {
3966 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3967 }
3968 }
3969 return NO_ERROR;
3970}
3971
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003972sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003973 audio_io_handle_t output, routing_strategy strategy)
3974{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003975 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003976 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003977 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3978 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003979 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003980 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003981 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3982 source = sourceDesc;
3983 break;
3984 }
3985 }
3986 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003987}
3988
Eric Laurente552edb2014-03-10 17:42:56 -07003989// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003990// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003991// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003992uint32_t AudioPolicyManager::nextAudioPortGeneration()
3993{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003994 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003995}
3996
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003997// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3998static const char *kConfigLocationList[] =
3999 {"/odm/etc", "/vendor/etc", "/system/etc"};
4000static const int kConfigLocationListSize =
4001 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
4002
4003static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4004 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004005 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004006 status_t ret;
4007
Petri Gyntherf497f292018-04-17 18:46:10 -07004008 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
4009 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4010 // A2DP offload supported but disabled: try to use special XML file
4011 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4012 }
4013 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4014
4015 for (const char* fileName : fileNames) {
4016 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004017 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4018 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004019 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004020 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004021 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004022 return ret;
4023 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004024 }
4025 }
4026 return ret;
4027}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004028
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004029AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4030 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004031 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004032 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004033 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004034 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004035 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004036 mVolumeCurves(new VolumeCurvesCollection()),
4037 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08004038 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004039 mAudioPortGeneration(1),
4040 mBeaconMuteRefCount(0),
4041 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004042 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004043 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004044 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004045 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004046{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004047}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004048
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004049AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4050 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4051{
4052 loadConfig();
4053 initialize();
4054}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004055
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004056// This check is to catch any legacy platform updating to Q without having
4057// switched to XML since its deprecation on O.
4058// TODO: after Q release, remove this check and flag as XML is now the only
4059// option and all legacy platform should have transitioned to XML.
4060#ifndef USE_XML_AUDIO_POLICY_CONF
4061#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004062#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004063
4064void AudioPolicyManager::loadConfig() {
4065 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004066 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004067 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004068 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004069}
4070
4071status_t AudioPolicyManager::initialize() {
4072 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004073
4074 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004075 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4076 if (!engineInstance) {
4077 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004078 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004079 }
4080 // Retrieve the Policy Manager Interface
4081 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4082 if (mEngine == NULL) {
4083 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004084 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004085 }
4086 mEngine->setObserver(this);
4087 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004088 if (status != NO_ERROR) {
4089 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4090 return status;
4091 }
François Gaffie2110e042015-03-24 08:41:51 +01004092
Eric Laurent3a4311c2014-03-17 12:00:47 -07004093 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004094 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004095 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004096 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004097 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4098 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004099 continue;
4100 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004101 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004102 // open all output streams needed to access attached devices
4103 // except for direct output streams that are only opened when they are actually
4104 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004105 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004106 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004107 if (!outProfile->canOpenNewIo()) {
4108 ALOGE("Invalid Output profile max open count %u for profile %s",
4109 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4110 continue;
4111 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004112 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004113 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004114 continue;
4115 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004116 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004117 mTtsOutputAvailable = true;
4118 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004119
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004120 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004121 continue;
4122 }
François Gaffie11d30102018-11-02 16:09:09 +01004123 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4124 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4125 sp<DeviceDescriptor> supportedDevice = 0;
4126 if (supportedDevices.contains(mDefaultOutputDevice)) {
4127 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004128 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004129 // choose first device present in profile's SupportedDevices also part of
4130 // mAvailableOutputDevices.
4131 if (availProfileDevices.isEmpty()) {
4132 continue;
4133 }
4134 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004135 }
François Gaffie11d30102018-11-02 16:09:09 +01004136 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004137 continue;
4138 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004139 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4140 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004141 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004142 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4143 AUDIO_STREAM_DEFAULT,
4144 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004145 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004146 ALOGW("Cannot open output stream for devices %s on hw module %s",
4147 supportedDevice->toString().c_str(), hwModule->getName());
4148 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004149 }
François Gaffie11d30102018-11-02 16:09:09 +01004150 for (const auto &device : availProfileDevices) {
4151 // give a valid ID to an attached device once confirmed it is reachable
4152 if (!device->isAttached()) {
4153 device->attach(hwModule);
4154 }
4155 }
4156 if (mPrimaryOutput == 0 &&
4157 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4158 mPrimaryOutput = outputDesc;
4159 }
4160 addOutput(output, outputDesc);
4161 setOutputDevices(outputDesc,
4162 DeviceVector(supportedDevice),
4163 true,
4164 0,
4165 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004166 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004167 // open input streams needed to access attached devices to validate
4168 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004169 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004170 if (!inProfile->canOpenNewIo()) {
4171 ALOGE("Invalid Input profile max open count %u for profile %s",
4172 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4173 continue;
4174 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004175 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004176 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004177 continue;
4178 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004179 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004180 // available input devices
4181 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4182 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4183 if (availProfileDevices.isEmpty()) {
4184 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004185 continue;
4186 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004187 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004188 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004189
Eric Laurentd78f1532014-09-16 16:38:20 -07004190 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004191 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004192 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004193 AUDIO_SOURCE_MIC,
4194 AUDIO_INPUT_FLAG_NONE,
4195 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004196 if (status != NO_ERROR) {
4197 ALOGW("Cannot open input stream for device %s on hw module %s",
4198 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004199 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004200 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004201 }
François Gaffie11d30102018-11-02 16:09:09 +01004202 for (const auto &device : availProfileDevices) {
4203 // give a valid ID to an attached device once confirmed it is reachable
4204 if (!device->isAttached()) {
4205 device->attach(hwModule);
4206 device->importAudioPort(inProfile, true);
4207 }
4208 }
4209 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004210 }
4211 }
4212 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004213 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004214 for (size_t i = 0; i < devices.size();) {
4215 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004216 if (!device->isAttached()) {
4217 ALOGW("device %s is unreachable", device->toString().c_str());
4218 devices.remove(device);
4219 continue;
4220 }
4221 // Device is now validated and can be appended to the available devices of the engine
4222 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004223 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004224 }
François Gaffie11d30102018-11-02 16:09:09 +01004225 };
4226 checkAndSetAvailable(mAvailableOutputDevices);
4227 checkAndSetAvailable(mAvailableInputDevices);
4228
Eric Laurent3a4311c2014-03-17 12:00:47 -07004229 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004230 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4231 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4232 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004233 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004234 }
jiabin9ff780e2018-03-19 18:19:52 -07004235 // If microphones address is empty, set it according to device type
4236 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004237 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004238 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004239 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004240 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004241 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004242 }
4243 }
4244 }
Eric Laurente552edb2014-03-10 17:42:56 -07004245
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004246 if (mPrimaryOutput == 0) {
4247 ALOGE("Failed to open primary output");
4248 status = NO_INIT;
4249 }
Eric Laurente552edb2014-03-10 17:42:56 -07004250
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004251 // Silence ALOGV statements
4252 property_set("log.tag." LOG_TAG, "D");
4253
Eric Laurente552edb2014-03-10 17:42:56 -07004254 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004255 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004256}
4257
Eric Laurente0720872014-03-11 09:30:41 -07004258AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004259{
Eric Laurente552edb2014-03-10 17:42:56 -07004260 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004261 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004262 }
4263 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004264 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004265 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004266 mAvailableOutputDevices.clear();
4267 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004268 mOutputs.clear();
4269 mInputs.clear();
4270 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004271 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004272 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004273}
4274
Eric Laurente0720872014-03-11 09:30:41 -07004275status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004276{
Eric Laurent87ffa392015-05-22 10:32:38 -07004277 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004278}
4279
Eric Laurente552edb2014-03-10 17:42:56 -07004280// ---
4281
Eric Laurent98e38192018-02-15 18:31:53 -08004282void AudioPolicyManager::addOutput(audio_io_handle_t output,
4283 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004284{
Eric Laurent1c333e22014-05-20 10:48:17 -07004285 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004286 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004287 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004288 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004289 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004290}
4291
François Gaffie53615e22015-03-19 09:24:12 +01004292void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4293{
4294 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004295 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004296}
4297
Eric Laurent98e38192018-02-15 18:31:53 -08004298void AudioPolicyManager::addInput(audio_io_handle_t input,
4299 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004300{
Eric Laurent1c333e22014-05-20 10:48:17 -07004301 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004303}
Eric Laurente552edb2014-03-10 17:42:56 -07004304
François Gaffie11d30102018-11-02 16:09:09 +01004305status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004306 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004307 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004308{
François Gaffie11d30102018-11-02 16:09:09 +01004309 audio_devices_t deviceType = device->type();
4310 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004311 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004312
François Gaffie11d30102018-11-02 16:09:09 +01004313 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004314 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004315 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004316 }
Eric Laurente552edb2014-03-10 17:42:56 -07004317
Eric Laurent3b73df72014-03-11 09:06:29 -07004318 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004319 // first list already open outputs that can be routed to this device
4320 for (size_t i = 0; i < mOutputs.size(); i++) {
4321 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004322 if (!desc->isDuplicated() && desc->supportsDevice(device)
4323 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004324 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4325 mOutputs.keyAt(i), device->toString().c_str());
4326 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004327 }
4328 }
4329 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004330 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004331 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004332 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4333 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004334 if (profile->supportsDevice(device)) {
4335 profiles.add(profile);
4336 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4337 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004338 }
4339 }
4340 }
4341
Eric Laurent7b279bb2015-12-14 10:18:23 -08004342 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004343
Eric Laurente552edb2014-03-10 17:42:56 -07004344 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004345 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004346 return BAD_VALUE;
4347 }
4348
4349 // open outputs for matching profiles if needed. Direct outputs are also opened to
4350 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4351 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004352 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004353
4354 // nothing to do if one output is already opened for this profile
4355 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 for (j = 0; j < outputs.size(); j++) {
4357 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004358 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004359 // matching profile: save the sample rates, format and channel masks supported
4360 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004361 if (audio_device_is_digital(deviceType)) {
4362 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004363 }
Eric Laurente552edb2014-03-10 17:42:56 -07004364 break;
4365 }
4366 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004367 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004368 continue;
4369 }
4370
Eric Laurent3974e3b2017-12-07 17:58:43 -08004371 if (!profile->canOpenNewIo()) {
4372 ALOGW("Max Output number %u already opened for this profile %s",
4373 profile->maxOpenCount, profile->getTagName().c_str());
4374 continue;
4375 }
4376
Eric Laurent83efe1c2017-07-09 16:51:08 -07004377 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004378 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004379 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004380 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004381 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004382 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004383
Eric Laurentfe231122017-11-17 17:48:06 -08004384 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004385 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004386 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004387 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004388 mpClientInterface->setParameters(output, String8(param));
4389 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004390 }
François Gaffie11d30102018-11-02 16:09:09 +01004391 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004392 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004393 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004394 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004395 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004396 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004397 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004398 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004399 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4400 profile->pickAudioProfile(
4401 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004402 config.offload_info.sample_rate = config.sample_rate;
4403 config.offload_info.channel_mask = config.channel_mask;
4404 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004405
François Gaffie11d30102018-11-02 16:09:09 +01004406 status_t status = desc->open(&config, DeviceVector(device),
4407 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004408 AUDIO_OUTPUT_FLAG_NONE, &output);
4409 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004410 output = AUDIO_IO_HANDLE_NONE;
4411 }
Eric Laurentd4692962014-05-05 18:13:44 -07004412 }
4413
Eric Laurentcf2c0212014-07-25 16:20:43 -07004414 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004416 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004417 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004418 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4419 policyMix->setOutput(desc);
4420 desc->mPolicyMix = policyMix->getMix();
4421 } else {
4422 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004423 address.string());
4424 }
François Gaffie036e1e92015-03-19 10:16:24 +01004425
Eric Laurent87ffa392015-05-22 10:32:38 -07004426 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4427 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004428 // no duplicated output for direct outputs and
4429 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004430 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004431
Eric Laurentd4692962014-05-05 18:13:44 -07004432 //TODO: configure audio effect output stage here
4433
4434 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004435 sp<SwAudioOutputDescriptor> dupOutputDesc =
4436 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4437 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4438 &duplicatedOutput);
4439 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004440 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004441 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004442 } else {
4443 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004444 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004445 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004446 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004448 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004449 }
Eric Laurente552edb2014-03-10 17:42:56 -07004450 }
4451 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 } else {
4453 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004454 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004455 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004456 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004457 profiles.removeAt(profile_index);
4458 profile_index--;
4459 } else {
4460 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004461 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004462 if (audio_device_is_digital(deviceType)) {
4463 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004464 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004465
François Gaffie11d30102018-11-02 16:09:09 +01004466 if (device_distinguishes_on_address(deviceType)) {
4467 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4468 device->toString().c_str());
4469 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4470 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004471 }
Eric Laurente552edb2014-03-10 17:42:56 -07004472 ALOGV("checkOutputsForDevice(): adding output %d", output);
4473 }
4474 }
4475
4476 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004477 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004478 return BAD_VALUE;
4479 }
Eric Laurentd4692962014-05-05 18:13:44 -07004480 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004481 // check if one opened output is not needed any more after disconnecting one device
4482 for (size_t i = 0; i < mOutputs.size(); i++) {
4483 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004484 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004485 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004486 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4487 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004488 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004489 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004490 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4491 mOutputs.keyAt(i));
4492 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004493 }
Eric Laurente552edb2014-03-10 17:42:56 -07004494 }
4495 }
Eric Laurentd4692962014-05-05 18:13:44 -07004496 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004497 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004498 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4499 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004500 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004501 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004502 "clearing direct output profile %zu on module %s",
4503 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004504 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004505 }
4506 }
4507 }
4508 }
4509 return NO_ERROR;
4510}
4511
François Gaffie11d30102018-11-02 16:09:09 +01004512status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004513 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004514 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004515{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004516 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004517
François Gaffie11d30102018-11-02 16:09:09 +01004518 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004519 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004520 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004521 }
4522
Eric Laurentd4692962014-05-05 18:13:44 -07004523 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4524 // first list already open inputs that can be routed to this device
4525 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4526 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004527 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004528 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4529 inputs.add(mInputs.keyAt(input_index));
4530 }
4531 }
4532
4533 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004534 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004535 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004536 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004537 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004538 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004539 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004540
François Gaffie11d30102018-11-02 16:09:09 +01004541 if (profile->supportsDevice(device)) {
4542 profiles.add(profile);
4543 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4544 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004545 }
4546 }
4547 }
4548
4549 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004550 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004551 return BAD_VALUE;
4552 }
4553
4554 // open inputs for matching profiles if needed. Direct inputs are also opened to
4555 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4556 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4557
Eric Laurent1c333e22014-05-20 10:48:17 -07004558 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004559
Eric Laurentd4692962014-05-05 18:13:44 -07004560 // nothing to do if one input is already opened for this profile
4561 size_t input_index;
4562 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4563 desc = mInputs.valueAt(input_index);
4564 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004565 if (audio_device_is_digital(device->type())) {
4566 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004567 }
Eric Laurentd4692962014-05-05 18:13:44 -07004568 break;
4569 }
4570 }
4571 if (input_index != mInputs.size()) {
4572 continue;
4573 }
4574
Eric Laurent3974e3b2017-12-07 17:58:43 -08004575 if (!profile->canOpenNewIo()) {
4576 ALOGW("Max Input number %u already opened for this profile %s",
4577 profile->maxOpenCount, profile->getTagName().c_str());
4578 continue;
4579 }
4580
Eric Laurentfe231122017-11-17 17:48:06 -08004581 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004582 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004583 status_t status = desc->open(nullptr,
4584 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004585 AUDIO_SOURCE_MIC,
4586 AUDIO_INPUT_FLAG_NONE,
4587 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004588
Eric Laurentcf2c0212014-07-25 16:20:43 -07004589 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004590 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004591 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004592 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004593 mpClientInterface->setParameters(input, String8(param));
4594 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004595 }
François Gaffie11d30102018-11-02 16:09:09 +01004596 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004597 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004598 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004599 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004600 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004601 }
4602
4603 if (input != 0) {
4604 addInput(input, desc);
4605 }
4606 } // endif input != 0
4607
Eric Laurentcf2c0212014-07-25 16:20:43 -07004608 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004609 ALOGW("%s could not open input for device %s", __func__,
4610 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004611 profiles.removeAt(profile_index);
4612 profile_index--;
4613 } else {
4614 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004615 if (audio_device_is_digital(device->type())) {
4616 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004617 }
Eric Laurentd4692962014-05-05 18:13:44 -07004618 ALOGV("checkInputsForDevice(): adding input %d", input);
4619 }
4620 } // end scan profiles
4621
4622 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004623 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004624 return BAD_VALUE;
4625 }
4626 } else {
4627 // Disconnect
4628 // check if one opened input is not needed any more after disconnecting one device
4629 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4630 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004631 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004632 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4633 mInputs.keyAt(input_index));
4634 inputs.add(mInputs.keyAt(input_index));
4635 }
4636 }
4637 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004638 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004639 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004640 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004641 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004642 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004643 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004644 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4645 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004646 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004647 }
4648 }
4649 }
4650 } // end disconnect
4651
4652 return NO_ERROR;
4653}
4654
4655
Eric Laurente0720872014-03-11 09:30:41 -07004656void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004657{
4658 ALOGV("closeOutput(%d)", output);
4659
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 if (outputDesc == NULL) {
4662 ALOGW("closeOutput() unknown output %d", output);
4663 return;
4664 }
François Gaffie036e1e92015-03-19 10:16:24 +01004665 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004666
Eric Laurente552edb2014-03-10 17:42:56 -07004667 // look for duplicated outputs connected to the output being removed.
4668 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004669 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004670 if (dupOutputDesc->isDuplicated() &&
4671 (dupOutputDesc->mOutput1 == outputDesc ||
4672 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004673 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004674 if (dupOutputDesc->mOutput1 == outputDesc) {
4675 outputDesc2 = dupOutputDesc->mOutput2;
4676 } else {
4677 outputDesc2 = dupOutputDesc->mOutput1;
4678 }
4679 // As all active tracks on duplicated output will be deleted,
4680 // and as they were also referenced on the other output, the reference
4681 // count for their stream type must be adjusted accordingly on
4682 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004683 const bool wasActive = outputDesc2->isActive();
4684 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4685 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
Eric Laurent733ce942017-12-07 12:18:25 -08004687 // stop() will be a no op if the output is still active but is needed in case all
4688 // active streams refcounts where cleared above
4689 if (wasActive) {
4690 outputDesc2->stop();
4691 }
Eric Laurente552edb2014-03-10 17:42:56 -07004692 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4693 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4694
4695 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004696 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004697 }
4698 }
4699
Eric Laurent05b90f82014-08-27 15:32:29 -07004700 nextAudioPortGeneration();
4701
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004702 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004703 if (index >= 0) {
4704 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004705 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004706 mAudioPatches.removeItemsAt(index);
4707 mpClientInterface->onAudioPatchListUpdate();
4708 }
4709
Eric Laurentfe231122017-11-17 17:48:06 -08004710 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004711
François Gaffie53615e22015-03-19 09:24:12 +01004712 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004714
4715 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4716 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004717 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004718 bool directOutputOpen = false;
4719 for (size_t i = 0; i < mOutputs.size(); i++) {
4720 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4721 directOutputOpen = true;
4722 break;
4723 }
4724 }
4725 if (!directOutputOpen) {
4726 ALOGV("no direct outputs open, reset MSD patch");
4727 setMsdPatch();
4728 }
4729 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004730}
4731
4732void AudioPolicyManager::closeInput(audio_io_handle_t input)
4733{
4734 ALOGV("closeInput(%d)", input);
4735
4736 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4737 if (inputDesc == NULL) {
4738 ALOGW("closeInput() unknown input %d", input);
4739 return;
4740 }
4741
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004743
François Gaffie11d30102018-11-02 16:09:09 +01004744 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004745 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004746 if (index >= 0) {
4747 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004748 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004749 mAudioPatches.removeItemsAt(index);
4750 mpClientInterface->onAudioPatchListUpdate();
4751 }
4752
Eric Laurentfe231122017-11-17 17:48:06 -08004753 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004754 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004755
François Gaffie11d30102018-11-02 16:09:09 +01004756 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4757 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004758 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4759 SoundTrigger::setCaptureState(false);
4760 }
Eric Laurente552edb2014-03-10 17:42:56 -07004761}
4762
François Gaffie11d30102018-11-02 16:09:09 +01004763SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4764 const DeviceVector &devices,
4765 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004766{
4767 SortedVector<audio_io_handle_t> outputs;
4768
François Gaffie11d30102018-11-02 16:09:09 +01004769 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004770 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004771 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004772 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004773 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004774 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4775 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004776 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004777 outputs.add(openOutputs.keyAt(i));
4778 }
4779 }
4780 return outputs;
4781}
4782
Mikhail Naganov37977152018-07-11 15:54:44 -07004783void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4784{
4785 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4786 // output is suspended before any tracks are moved to it
4787 checkA2dpSuspend();
4788 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004789 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004790 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004791 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004792 setMsdPatch();
4793 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004794}
4795
Eric Laurente0720872014-03-11 09:30:41 -07004796void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004797{
François Gaffie11d30102018-11-02 16:09:09 +01004798 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4799 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4800 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4801 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004802
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004803 // also take into account external policy-related changes: add all outputs which are
4804 // associated with policies in the "before" and "after" output vectors
4805 ALOGVV("checkOutputForStrategy(): policy related outputs");
4806 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004807 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004808 if (desc != 0 && desc->mPolicyMix != NULL) {
4809 srcOutputs.add(desc->mIoHandle);
4810 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4811 }
4812 }
4813 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004814 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004815 if (desc != 0 && desc->mPolicyMix != NULL) {
4816 dstOutputs.add(desc->mIoHandle);
4817 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4818 }
4819 }
4820
Francois Gaffie716e1432019-01-14 16:58:59 +01004821 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004822 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4823 // audio from invalidated tracks will be rendered when unmuting
4824 uint32_t maxLatency = 0;
4825 for (audio_io_handle_t srcOut : srcOutputs) {
4826 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4827 if (desc != 0 && maxLatency < desc->latency()) {
4828 maxLatency = desc->latency();
4829 }
4830 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004831 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4832 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4833 std::to_string(srcOutputs[0]).c_str(),
4834 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004835 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004836 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004837 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4838 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004839 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004840 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4841 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004842 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004843 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004844 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004845 if (source != 0){
4846 connectAudioSource(source);
4847 }
Eric Laurente552edb2014-03-10 17:42:56 -07004848 }
4849
4850 // Move effects associated to this strategy from previous output to new output
4851 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004852 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004853 }
4854 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004855 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004856 if (getStrategy((audio_stream_type_t)i) == strategy) {
4857 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004858 }
4859 }
4860 }
4861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004864{
François Gaffie2110e042015-03-24 08:41:51 +01004865 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004866 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004867 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004868 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004869 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004870 checkOutputForStrategy(STRATEGY_SONIFICATION);
4871 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004872 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004873 checkOutputForStrategy(STRATEGY_MEDIA);
4874 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004875 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004876}
4877
Eric Laurente0720872014-03-11 09:30:41 -07004878void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004879{
François Gaffie53615e22015-03-19 09:24:12 +01004880 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004881 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004882 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004883 return;
4884 }
4885
Eric Laurent3a4311c2014-03-17 12:00:47 -07004886 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004887 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4888 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4889 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004890
4891 // if suspended, restore A2DP output if:
4892 // ((SCO device is NOT connected) ||
4893 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4894 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004895 //
Eric Laurentf732e072016-08-03 19:30:28 -07004896 // if not suspended, suspend A2DP output if:
4897 // (SCO device is connected) &&
4898 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4899 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004900 //
4901 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004902 if (!isScoConnected ||
4903 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4904 AUDIO_POLICY_FORCE_BT_SCO) &&
4905 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4906 AUDIO_POLICY_FORCE_BT_SCO) &&
4907 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004908 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004909
4910 mpClientInterface->restoreOutput(a2dpOutput);
4911 mA2dpSuspended = false;
4912 }
4913 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004914 if (isScoConnected &&
4915 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4916 AUDIO_POLICY_FORCE_BT_SCO) ||
4917 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4918 AUDIO_POLICY_FORCE_BT_SCO) ||
4919 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004920 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004921
4922 mpClientInterface->suspendOutput(a2dpOutput);
4923 mA2dpSuspended = true;
4924 }
4925 }
4926}
4927
Eric Laurent97ac8712018-07-27 18:59:02 -07004928template <class IoDescriptor, class Filter>
4929sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4930 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4931{
4932 auto activeClients = desc->clientsList(true /*activeOnly*/);
4933 auto activeClientsWithRoute =
4934 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4935 active = activeClients.size() > 0;
4936 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4937 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4938 }
4939 return nullptr;
4940}
4941
4942template <class IoCollection, class Filter>
4943sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4944 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4945{
4946 sp<DeviceDescriptor> device;
4947 for (size_t i = 0; i < ioCollection.size(); i++) {
4948 auto desc = ioCollection.valueAt(i);
4949 bool active;
4950 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4951 if (active && curDevice == nullptr) {
4952 return nullptr;
4953 } else if (curDevice != nullptr) {
4954 device = curDevice;
4955 }
4956 }
4957 return device;
4958}
4959
François Gaffie11d30102018-11-02 16:09:09 +01004960DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4961 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004962{
François Gaffie11d30102018-11-02 16:09:09 +01004963 DeviceVector devices;
4964
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004965 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 if (index >= 0) {
4967 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4968 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004969 ALOGV("%s device %s forced by patch %d", __func__,
4970 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4971 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004972 }
4973 }
4974
Eric Laurent97ac8712018-07-27 18:59:02 -07004975 // Honor explicit routing requests only if no client using default routing is active on this
4976 // input: a specific app can not force routing for other apps by setting a preferred device.
4977 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004978 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004979 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004980 if (device != nullptr) {
4981 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004982 }
4983
François Gaffiea807ef92018-11-05 10:44:33 +01004984 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
4985 // of setForceUse / Default Bus device here
4986 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
4987 if (device != nullptr) {
4988 return DeviceVector(device);
4989 }
4990
Eric Laurente552edb2014-03-10 17:42:56 -07004991 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004992 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004993 // use device for strategy enforced audible
4994 // 2: we are in call or the strategy phone is active on the output:
4995 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004996 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004997 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004998 // 4: the strategy for enforced audible is active but not enforced on the output:
4999 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08005000 // 5: the strategy accessibility is active on the output:
5001 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07005002 // 6: the strategy "respectful" sonification is active on the output:
5003 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08005004 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07005005 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08005006 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07005007 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08005008 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005009 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07005010
5011 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
5012 // with a refined rule considering mutually exclusive devices (using same backend)
5013 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01005014 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005015 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01005016 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005017 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07005018 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005019 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08005020 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01005021 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07005022 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01005023 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08005024 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01005025 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005026 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01005027 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005028 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01005029 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005030 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01005031 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005032 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01005033 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01005034 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01005035 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07005036 }
5037
François Gaffie11d30102018-11-02 16:09:09 +01005038 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
5039 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005040}
5041
François Gaffie11d30102018-11-02 16:09:09 +01005042sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5043 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005044{
François Gaffie11d30102018-11-02 16:09:09 +01005045 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005046
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005047 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 if (index >= 0) {
5049 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5050 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005051 ALOGV("getNewInputDevice() device %s forced by patch %d",
5052 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5053 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 }
5055 }
5056
Eric Laurent97ac8712018-07-27 18:59:02 -07005057 // Honor explicit routing requests only if no client using default routing is active on this
5058 // input: a specific app can not force routing for other apps by setting a preferred device.
5059 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005060 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5061 if (device != nullptr) {
5062 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005063 }
5064
Eric Laurentdc95a252018-04-12 12:46:56 -07005065 // If we are not in call and no client is active on this input, this methods returns
5066 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005067 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5068 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5069 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005070 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005071 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5072 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005073 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005074
Eric Laurente552edb2014-03-10 17:42:56 -07005075 return device;
5076}
5077
Eric Laurent794fde22016-03-11 09:50:45 -08005078bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5079 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005080 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005081}
5082
Eric Laurente0720872014-03-11 09:30:41 -07005083uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005084 return (uint32_t)getStrategy(stream);
5085}
5086
Eric Laurente0720872014-03-11 09:30:41 -07005087audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005088 // By checking the range of stream before calling getStrategy, we avoid
5089 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5090 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005091 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 return AUDIO_DEVICE_NONE;
5093 }
François Gaffie11d30102018-11-02 16:09:09 +01005094 DeviceVector activeDevices;
5095 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005096 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5097 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005098 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 }
Eric Laurent794fde22016-03-11 09:50:45 -08005100 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005101 DeviceVector curDevices =
5102 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5103 devices.merge(curDevices);
5104 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005105 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005106 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005107 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005108 }
5109 }
Eric Laurente552edb2014-03-10 17:42:56 -07005110 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005111
Eric Laurentb0688d62018-08-14 15:49:18 -07005112 // Favor devices selected on active streams if any to report correct device in case of
5113 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005114 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005115 devices = activeDevices;
5116 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005117 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5118 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005119 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5120 if (!speakerSafeDevices.isEmpty()) {
5121 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5122 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005123 }
François Gaffie11d30102018-11-02 16:09:09 +01005124 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005125}
5126
François Gaffie2110e042015-03-24 08:41:51 +01005127routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5128{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005129 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005130 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005131}
5132
Eric Laurent97ac8712018-07-27 18:59:02 -07005133routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005134 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005135 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005136 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005137 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005138 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005139 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005140 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005141 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005142 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005143}
5144
Eric Laurente0720872014-03-11 09:30:41 -07005145void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005146 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005147 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005148 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5149 updateDevicesAndOutputs();
5150 break;
5151 default:
5152 break;
5153 }
5154}
5155
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005156uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005157
5158 // skip beacon mute management if a dedicated TTS output is available
5159 if (mTtsOutputAvailable) {
5160 return 0;
5161 }
5162
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005163 switch(event) {
5164 case STARTING_OUTPUT:
5165 mBeaconMuteRefCount++;
5166 break;
5167 case STOPPING_OUTPUT:
5168 if (mBeaconMuteRefCount > 0) {
5169 mBeaconMuteRefCount--;
5170 }
5171 break;
5172 case STARTING_BEACON:
5173 mBeaconPlayingRefCount++;
5174 break;
5175 case STOPPING_BEACON:
5176 if (mBeaconPlayingRefCount > 0) {
5177 mBeaconPlayingRefCount--;
5178 }
5179 break;
5180 }
5181
5182 if (mBeaconMuteRefCount > 0) {
5183 // any playback causes beacon to be muted
5184 return setBeaconMute(true);
5185 } else {
5186 // no other playback: unmute when beacon starts playing, mute when it stops
5187 return setBeaconMute(mBeaconPlayingRefCount == 0);
5188 }
5189}
5190
5191uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5192 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5193 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5194 // keep track of muted state to avoid repeating mute/unmute operations
5195 if (mBeaconMuted != mute) {
5196 // mute/unmute AUDIO_STREAM_TTS on all outputs
5197 ALOGV("\t muting %d", mute);
5198 uint32_t maxLatency = 0;
5199 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005201 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005202 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005203 0 /*delay*/, AUDIO_DEVICE_NONE);
5204 const uint32_t latency = desc->latency() * 2;
5205 if (latency > maxLatency) {
5206 maxLatency = latency;
5207 }
5208 }
5209 mBeaconMuted = mute;
5210 return maxLatency;
5211 }
5212 return 0;
5213}
5214
François Gaffie11d30102018-11-02 16:09:09 +01005215DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005216{
Eric Laurent97ac8712018-07-27 18:59:02 -07005217 // Honor explicit routing requests only if all active clients have a preferred route in which
5218 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005219 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5220 if (device != nullptr) {
5221 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005222 }
5223
Eric Laurente552edb2014-03-10 17:42:56 -07005224 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005225 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5226 mDevicesForStrategy[strategy].toString().c_str());
5227 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005228 }
François Gaffie11d30102018-11-02 16:09:09 +01005229 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005230}
5231
Eric Laurente0720872014-03-11 09:30:41 -07005232void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005233{
5234 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005235 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005236 }
5237 mPreviousOutputs = mOutputs;
5238}
5239
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005240uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005241 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005242 uint32_t delayMs)
5243{
5244 // mute/unmute strategies using an incompatible device combination
5245 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5246 // if unmuting, unmute only after the specified delay
5247 if (outputDesc->isDuplicated()) {
5248 return 0;
5249 }
5250
5251 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005252 audio_devices_t deviceType = outputDesc->devices().types();
5253 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005254
5255 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005256 audio_devices_t curDeviceType =
5257 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5258 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5259 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005260 bool doMute = false;
5261
5262 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5263 doMute = true;
5264 outputDesc->mStrategyMutedByDevice[i] = true;
5265 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5266 doMute = true;
5267 outputDesc->mStrategyMutedByDevice[i] = false;
5268 }
Eric Laurent99401132014-05-07 19:48:15 -07005269 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005270 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005271 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005272 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005273 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005274 continue;
5275 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005276 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005277 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005278 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005279 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005280 if (mute) {
5281 // FIXME: should not need to double latency if volume could be applied
5282 // immediately by the audioflinger mixer. We must account for the delay
5283 // between now and the next time the audioflinger thread for this output
5284 // will process a buffer (which corresponds to one buffer size,
5285 // usually 1/2 or 1/4 of the latency).
5286 if (muteWaitMs < desc->latency() * 2) {
5287 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005288 }
5289 }
5290 }
5291 }
5292 }
5293 }
5294
Eric Laurent99401132014-05-07 19:48:15 -07005295 // temporary mute output if device selection changes to avoid volume bursts due to
5296 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005297 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005298 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5299 // temporary mute duration is conservatively set to 4 times the reported latency
5300 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5301 if (muteWaitMs < tempMuteWaitMs) {
5302 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005303 }
Eric Laurentdc462862016-07-19 12:29:53 -07005304
Eric Laurent99401132014-05-07 19:48:15 -07005305 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005306 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005307 // make sure that we do not start the temporary mute period too early in case of
5308 // delayed device change
5309 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005310 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005311 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005312 }
5313 }
5314 }
5315
Eric Laurente552edb2014-03-10 17:42:56 -07005316 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5317 if (muteWaitMs > delayMs) {
5318 muteWaitMs -= delayMs;
5319 usleep(muteWaitMs * 1000);
5320 return muteWaitMs;
5321 }
5322 return 0;
5323}
5324
François Gaffie11d30102018-11-02 16:09:09 +01005325uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5326 const DeviceVector &devices,
5327 bool force,
5328 int delayMs,
5329 audio_patch_handle_t *patchHandle,
5330 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005331{
François Gaffie11d30102018-11-02 16:09:09 +01005332 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005333 uint32_t muteWaitMs;
5334
5335 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005336 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5337 nullptr /* patchHandle */, requiresMuteCheck);
5338 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5339 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005340 return muteWaitMs;
5341 }
Eric Laurente552edb2014-03-10 17:42:56 -07005342
5343 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005344 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005345
François Gaffie11d30102018-11-02 16:09:09 +01005346 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5347 // output profile
5348 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5349 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5350 return 0;
5351 }
Eric Laurente552edb2014-03-10 17:42:56 -07005352
François Gaffie11d30102018-11-02 16:09:09 +01005353 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005354
François Gaffie11d30102018-11-02 16:09:09 +01005355 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5356
5357 if (!filteredDevices.isEmpty()) {
5358 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005359 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005360
5361 // if the outputs are not materially active, there is no need to mute.
5362 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005363 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005364 } else {
5365 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5366 muteWaitMs = 0;
5367 }
Eric Laurente552edb2014-03-10 17:42:56 -07005368
5369 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005370 // the requested device is AUDIO_DEVICE_NONE
5371 // OR the requested device is the same as current device
5372 // AND force is not specified
5373 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005374 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005375 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005376 !force && outputDesc->getPatchHandle() != 0) {
5377 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5378 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005379 return muteWaitMs;
5380 }
5381
François Gaffie11d30102018-11-02 16:09:09 +01005382 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005383
Eric Laurente552edb2014-03-10 17:42:56 -07005384 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005385 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005386 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005387 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005388 PatchBuilder patchBuilder;
5389 patchBuilder.addSource(outputDesc);
5390 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5391 for (const auto &filteredDevice : filteredDevices) {
5392 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005393 }
5394
François Gaffie11d30102018-11-02 16:09:09 +01005395 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005396 }
Eric Laurente552edb2014-03-10 17:42:56 -07005397
5398 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005399 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005400
5401 return muteWaitMs;
5402}
5403
Eric Laurentc75307b2015-03-17 15:29:32 -07005404status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 int delayMs,
5406 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005407{
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 ssize_t index;
5409 if (patchHandle) {
5410 index = mAudioPatches.indexOfKey(*patchHandle);
5411 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005412 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 }
5414 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005415 return INVALID_OPERATION;
5416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5418 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005420 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 removeAudioPatch(patchDesc->mHandle);
5422 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005423 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005424 return status;
5425}
5426
5427status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005428 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 bool force,
5430 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005431{
5432 status_t status = NO_ERROR;
5433
Eric Laurent1f2f2232014-06-02 12:01:23 -07005434 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005435 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5436 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005437
François Gaffie11d30102018-11-02 16:09:09 +01005438 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005439 PatchBuilder patchBuilder;
5440 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005441 // AUDIO_SOURCE_HOTWORD is for internal use only:
5442 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005443 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5444 auto result = usecase;
5445 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5446 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5447 }
5448 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005449 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005450 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005451 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005452 }
5453 }
5454 return status;
5455}
5456
Eric Laurent6a94d692014-05-20 11:18:06 -07005457status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5458 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005459{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005460 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 ssize_t index;
5462 if (patchHandle) {
5463 index = mAudioPatches.indexOfKey(*patchHandle);
5464 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005465 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005466 }
5467 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005468 return INVALID_OPERATION;
5469 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5471 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005472 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005473 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005474 removeAudioPatch(patchDesc->mHandle);
5475 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005476 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005477 return status;
5478}
5479
François Gaffie11d30102018-11-02 16:09:09 +01005480sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005481 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005482 audio_format_t& format,
5483 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005484 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005485{
5486 // Choose an input profile based on the requested capture parameters: select the first available
5487 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005488 //
5489 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5490 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005491
Glenn Kasten730b9262018-03-29 15:01:26 -07005492 sp<IOProfile> firstInexact;
5493 uint32_t updatedSamplingRate = 0;
5494 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5495 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005496 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005497 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005498 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005499 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005500 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005501 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005502 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005503 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005504 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005505 &channelMask /*updatedChannelMask*/,
5506 // FIXME ugly cast
5507 (audio_output_flags_t) flags,
5508 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005509 return profile;
5510 }
François Gaffie11d30102018-11-02 16:09:09 +01005511 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005512 samplingRate,
5513 &updatedSamplingRate,
5514 format,
5515 &updatedFormat,
5516 channelMask,
5517 &updatedChannelMask,
5518 // FIXME ugly cast
5519 (audio_output_flags_t) flags,
5520 false /*exactMatchRequiredForInputFlags*/)) {
5521 firstInexact = profile;
5522 }
5523
Eric Laurente552edb2014-03-10 17:42:56 -07005524 }
5525 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005526 if (firstInexact != nullptr) {
5527 samplingRate = updatedSamplingRate;
5528 format = updatedFormat;
5529 channelMask = updatedChannelMask;
5530 return firstInexact;
5531 }
Eric Laurente552edb2014-03-10 17:42:56 -07005532 return NULL;
5533}
5534
Francois Gaffie716e1432019-01-14 16:58:59 +01005535sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5536 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005537{
Eric Laurent97ac8712018-07-27 18:59:02 -07005538 // Honor explicit routing requests only if all active clients have a preferred route in which
5539 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005540 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005541 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005542 if (device != nullptr) {
5543 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005544 }
5545
François Gaffie11d30102018-11-02 16:09:09 +01005546 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005547 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005548 policyMix);
5549 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005550 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005551}
5552
Francois Gaffie716e1432019-01-14 16:58:59 +01005553sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005554{
Francois Gaffie716e1432019-01-14 16:58:59 +01005555 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5556 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5557 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5558 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005559 String8(attributes.tags + strlen("addr=")),
5560 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005561 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005562 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005563}
5564
Eric Laurente0720872014-03-11 09:30:41 -07005565float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005566 int index,
5567 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005569 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005570
5571 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5572 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5573 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5574 // the ringtone volume
5575 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5576 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5577 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5578 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5579 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5580 }
5581
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005582 // in-call: always cap volume by voice volume + some low headroom
5583 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005584 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005585 switch (stream) {
5586 case AUDIO_STREAM_SYSTEM:
5587 case AUDIO_STREAM_RING:
5588 case AUDIO_STREAM_MUSIC:
5589 case AUDIO_STREAM_ALARM:
5590 case AUDIO_STREAM_NOTIFICATION:
5591 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5592 case AUDIO_STREAM_DTMF:
5593 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005594 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005595 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005596 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005597 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005598 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005599 if (volumeDB > maxVoiceVolDb) {
5600 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5601 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5602 volumeDB = maxVoiceVolDb;
5603 }
5604 } break;
5605 default:
5606 break;
5607 }
5608 }
5609
Eric Laurente552edb2014-03-10 17:42:56 -07005610 // if a headset is connected, apply the following rules to ring tones and notifications
5611 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005612 // - always attenuate notifications volume by 6dB
5613 // - attenuate ring tones volume by 6dB unless music is not playing and
5614 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005615 // - if music is playing, always limit the volume to current music volume,
5616 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005617 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005618 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5619 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5620 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005621 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005622 AUDIO_DEVICE_OUT_USB_HEADSET |
5623 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005624 ((stream_strategy == STRATEGY_SONIFICATION)
5625 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005626 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005627 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005628 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005629 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005630 // when the phone is ringing we must consider that music could have been paused just before
5631 // by the music application and behave as if music was active if the last music track was
5632 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005633 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005634 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005635 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005636 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005637 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005638 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5639 musicDevice),
5640 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005641 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5642 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005643 if (volumeDB > minVolDB) {
5644 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005645 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005646 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005647 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5648 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5649 // on A2DP, also ensure notification volume is not too low compared to media when
5650 // intended to be played
5651 if ((volumeDB > -96.0f) &&
5652 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5653 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5654 stream, device,
5655 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5656 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5657 }
5658 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005659 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5660 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005661 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005662 }
5663 }
5664
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005665 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005666}
5667
Eric Laurent3839bc02018-07-10 18:33:34 -07005668int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5669 audio_stream_type_t srcStream,
5670 audio_stream_type_t dstStream)
5671{
5672 if (srcStream == dstStream) {
5673 return srcIndex;
5674 }
5675 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5676 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5677 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5678 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5679
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005680 // preserve mute request or correct range
5681 if (srcIndex < minSrc) {
5682 if (srcIndex == 0) {
5683 return 0;
5684 }
5685 srcIndex = minSrc;
5686 } else if (srcIndex > maxSrc) {
5687 srcIndex = maxSrc;
5688 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005689 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5690}
5691
Eric Laurente0720872014-03-11 09:30:41 -07005692status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005693 int index,
5694 const sp<AudioOutputDescriptor>& outputDesc,
5695 audio_devices_t device,
5696 int delayMs,
5697 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005698{
Eric Laurente552edb2014-03-10 17:42:56 -07005699 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005700 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005701 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005702 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005703 return NO_ERROR;
5704 }
François Gaffie2110e042015-03-24 08:41:51 +01005705 audio_policy_forced_cfg_t forceUseForComm =
5706 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005707 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005708 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5709 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005710 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005711 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005712 return INVALID_OPERATION;
5713 }
5714
Eric Laurentc75307b2015-03-17 15:29:32 -07005715 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005716 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005717 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005718
Eric Laurentffbc80f2015-03-18 18:30:19 -07005719 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005720 if (outputDesc->isFixedVolume(device) ||
5721 // Force VoIP volume to max for bluetooth SCO
5722 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5723 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005724 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005725 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005726
Eric Laurentffbc80f2015-03-18 18:30:19 -07005727 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005728
Eric Laurent3b73df72014-03-11 09:06:29 -07005729 if (stream == AUDIO_STREAM_VOICE_CALL ||
5730 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005731 float voiceVolume;
5732 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005733 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005734 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005735 } else {
5736 voiceVolume = 1.0;
5737 }
5738
Eric Laurent18fba842016-03-31 14:41:26 -07005739 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005740 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5741 mLastVoiceVolume = voiceVolume;
5742 }
5743 }
5744
5745 return NO_ERROR;
5746}
5747
Eric Laurentc75307b2015-03-17 15:29:32 -07005748void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5749 audio_devices_t device,
5750 int delayMs,
5751 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005752{
Eric Laurentc75307b2015-03-17 15:29:32 -07005753 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005754
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 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005757 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005758 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005759 device,
5760 delayMs,
5761 force);
5762 }
5763}
5764
Eric Laurente0720872014-03-11 09:30:41 -07005765void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005766 bool on,
5767 const sp<AudioOutputDescriptor>& outputDesc,
5768 int delayMs,
5769 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005770{
Eric Laurent72249d52015-06-08 11:12:15 -07005771 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5772 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005773 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005774 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005775 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005776 }
5777 }
5778}
5779
Eric Laurente0720872014-03-11 09:30:41 -07005780void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005781 bool on,
5782 const sp<AudioOutputDescriptor>& outputDesc,
5783 int delayMs,
5784 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005785{
Eric Laurente552edb2014-03-10 17:42:56 -07005786 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005787 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005788 }
5789
Eric Laurentc75307b2015-03-17 15:29:32 -07005790 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5791 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005792
5793 if (on) {
5794 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005795 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005796 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005797 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005798 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005799 }
5800 }
5801 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5802 outputDesc->mMuteCount[stream]++;
5803 } else {
5804 if (outputDesc->mMuteCount[stream] == 0) {
5805 ALOGV("setStreamMute() unmuting non muted stream!");
5806 return;
5807 }
5808 if (--outputDesc->mMuteCount[stream] == 0) {
5809 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005810 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005811 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005812 device,
5813 delayMs);
5814 }
5815 }
5816}
5817
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005818audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5819{
5820 // flags to stream type mapping
5821 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5822 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5823 }
5824 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5825 return AUDIO_STREAM_BLUETOOTH_SCO;
5826 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005827 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5828 return AUDIO_STREAM_TTS;
5829 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005830
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005831 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005832}
Eric Laurente83b55d2014-11-14 10:06:21 -08005833
François Gaffie53615e22015-03-19 09:24:12 +01005834bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5835{
Eric Laurente83b55d2014-11-14 10:06:21 -08005836 // has flags that map to a strategy?
5837 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5838 return true;
5839 }
5840
5841 // has known usage?
5842 switch (paa->usage) {
5843 case AUDIO_USAGE_UNKNOWN:
5844 case AUDIO_USAGE_MEDIA:
5845 case AUDIO_USAGE_VOICE_COMMUNICATION:
5846 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5847 case AUDIO_USAGE_ALARM:
5848 case AUDIO_USAGE_NOTIFICATION:
5849 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5850 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5851 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5852 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5853 case AUDIO_USAGE_NOTIFICATION_EVENT:
5854 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5855 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5856 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5857 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005858 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005859 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005860 break;
5861 default:
5862 return false;
5863 }
5864 return true;
5865}
5866
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005867bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005868 routing_strategy strategy, uint32_t inPastMs,
5869 nsecs_t sysTime) const
5870{
5871 if ((sysTime == 0) && (inPastMs != 0)) {
5872 sysTime = systemTime();
5873 }
Eric Laurent794fde22016-03-11 09:50:45 -08005874 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005875 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005876 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005877 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5878 return true;
5879 }
5880 }
5881 return false;
5882}
5883
François Gaffie11d30102018-11-02 16:09:09 +01005884bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5885 routing_strategy strategy, uint32_t inPastMs,
5886 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005887{
5888 for (size_t i = 0; i < mOutputs.size(); i++) {
5889 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5890 if (outputDesc->sharesHwModuleWith(desc)
5891 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5892 return true;
5893 }
5894 }
5895 return false;
5896}
5897
François Gaffie2110e042015-03-24 08:41:51 +01005898audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5899{
5900 return mEngine->getForceUse(usage);
5901}
5902
5903bool AudioPolicyManager::isInCall()
5904{
5905 return isStateInCall(mEngine->getPhoneState());
5906}
5907
5908bool AudioPolicyManager::isStateInCall(int state)
5909{
5910 return is_state_in_call(state);
5911}
5912
Eric Laurentd60560a2015-04-10 11:31:20 -07005913void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5914{
5915 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005916 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5917 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5918 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5919 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005920 }
5921 }
5922
5923 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5924 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5925 bool release = false;
5926 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5927 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5928 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5929 source->ext.device.type == deviceDesc->type()) {
5930 release = true;
5931 }
5932 }
5933 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5934 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5935 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5936 sink->ext.device.type == deviceDesc->type()) {
5937 release = true;
5938 }
5939 }
5940 if (release) {
5941 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5942 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5943 }
5944 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005945
5946 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005947}
5948
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005949void AudioPolicyManager::modifySurroundFormats(
5950 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005951 std::unordered_set<audio_format_t> enforcedSurround(
5952 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005953 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5954 for (const auto& pair : mConfig.getSurroundFormats()) {
5955 allSurround.insert(pair.first);
5956 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5957 }
Phil Burk09bc4612016-02-24 15:58:15 -08005958
5959 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5960 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005961 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005962 // This is the resulting set of formats depending on the surround mode:
5963 // 'all surround' = allSurround
5964 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5965 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5966 // 'manual surround' = mManualSurroundFormats
5967 // AUTO: formats v 'enforced surround'
5968 // ALWAYS: formats v 'all surround' v 'enforced surround'
5969 // NEVER: formats ^ 'non-surround'
5970 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005971
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005972 std::unordered_set<audio_format_t> formatSet;
5973 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5974 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005975 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005976 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005977 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005978 formatSet.insert(*formatIter);
5979 }
5980 }
5981 } else {
5982 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5983 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005984 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005985
jiabin81772902018-04-02 17:52:27 -07005986 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005987 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005988 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5989 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5990 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005991 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005992 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5993 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5994 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005995 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005996 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005997 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005998 for (const auto& format : formatSet) {
5999 formatsPtr->push(format);
6000 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006001}
6002
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006003void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006004 ChannelsVector &channelMasks = *channelMasksPtr;
6005 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6006 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6007
6008 // If NEVER, then remove support for channelMasks > stereo.
6009 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6010 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6011 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6012 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6013 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6014 channelMasks.removeAt(maskIndex);
6015 } else {
6016 maskIndex++;
6017 }
6018 }
jiabin81772902018-04-02 17:52:27 -07006019 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6020 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6021 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006022 bool supports5dot1 = false;
6023 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006024 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006025 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6026 supports5dot1 = true;
6027 break;
6028 }
6029 }
6030 // If not then add 5.1 support.
6031 if (!supports5dot1) {
6032 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006033 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006034 }
Phil Burk09bc4612016-02-24 15:58:15 -08006035 }
6036}
6037
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006038void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006039 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006040 AudioProfileVector &profiles)
6041{
6042 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006043 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006044
François Gaffie112b0af2015-11-19 16:13:25 +01006045 // Format MUST be checked first to update the list of AudioProfile
6046 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006047 reply = mpClientInterface->getParameters(
6048 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006049 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006050 AudioParameter repliedParameters(reply);
6051 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006052 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006053 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6054 return;
6055 }
Phil Burk09bc4612016-02-24 15:58:15 -08006056 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006057 if (device == AUDIO_DEVICE_OUT_HDMI
6058 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006059 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006060 }
Phil Burk09bc4612016-02-24 15:58:15 -08006061 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006062 }
François Gaffie112b0af2015-11-19 16:13:25 +01006063
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006064 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006065 ChannelsVector channelMasks;
6066 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006067 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006068 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006069
6070 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006071 reply = mpClientInterface->getParameters(
6072 ioHandle,
6073 requestedParameters.toString() + ";" +
6074 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006075 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006076 AudioParameter repliedParameters(reply);
6077 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006078 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006079 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006080 }
6081 }
6082 if (profiles.hasDynamicChannelsFor(format)) {
6083 reply = mpClientInterface->getParameters(ioHandle,
6084 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006085 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006086 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006087 AudioParameter repliedParameters(reply);
6088 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006089 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006090 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006091 if (device == AUDIO_DEVICE_OUT_HDMI
6092 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006093 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006094 }
François Gaffie112b0af2015-11-19 16:13:25 +01006095 }
6096 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006097 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006098 }
6099}
Eric Laurentd60560a2015-04-10 11:31:20 -07006100
Mikhail Naganovdc769682018-05-04 15:34:08 -07006101status_t AudioPolicyManager::installPatch(const char *caller,
6102 audio_patch_handle_t *patchHandle,
6103 AudioIODescriptorInterface *ioDescriptor,
6104 const struct audio_patch *patch,
6105 int delayMs)
6106{
6107 ssize_t index = mAudioPatches.indexOfKey(
6108 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6109 *patchHandle : ioDescriptor->getPatchHandle());
6110 sp<AudioPatch> patchDesc;
6111 status_t status = installPatch(
6112 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6113 if (status == NO_ERROR) {
6114 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6115 }
6116 return status;
6117}
6118
6119status_t AudioPolicyManager::installPatch(const char *caller,
6120 ssize_t index,
6121 audio_patch_handle_t *patchHandle,
6122 const struct audio_patch *patch,
6123 int delayMs,
6124 uid_t uid,
6125 sp<AudioPatch> *patchDescPtr)
6126{
6127 sp<AudioPatch> patchDesc;
6128 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6129 if (index >= 0) {
6130 patchDesc = mAudioPatches.valueAt(index);
6131 afPatchHandle = patchDesc->mAfPatchHandle;
6132 }
6133
6134 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6135 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6136 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6137 if (status == NO_ERROR) {
6138 if (index < 0) {
6139 patchDesc = new AudioPatch(patch, uid);
6140 addAudioPatch(patchDesc->mHandle, patchDesc);
6141 } else {
6142 patchDesc->mPatch = *patch;
6143 }
6144 patchDesc->mAfPatchHandle = afPatchHandle;
6145 if (patchHandle) {
6146 *patchHandle = patchDesc->mHandle;
6147 }
6148 nextAudioPortGeneration();
6149 mpClientInterface->onAudioPatchListUpdate();
6150 }
6151 if (patchDescPtr) *patchDescPtr = patchDesc;
6152 return status;
6153}
6154
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006155} // namespace android