blob: 0ea3d728a84dd566a064b1edad3d48ffc1d13ab8 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080084 const char *device_name,
85 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -070086{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -080087 status_t status = setDeviceConnectionStateInt(device, state, device_address,
88 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080089 nextAudioPortGeneration();
90 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080091}
92
François Gaffie11d30102018-11-02 16:09:09 +010093void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
94 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020095{
François Gaffie11d30102018-11-02 16:09:09 +010096 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020097 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070098 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010099 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200100 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
101}
102
François Gaffie11d30102018-11-02 16:09:09 +0100103status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800104 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800105 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 const char *device_name,
107 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800109 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
110 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700111
112 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100113 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700114
François Gaffie11d30102018-11-02 16:09:09 +0100115 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800116 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100117 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
118 if (device == 0) {
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100123 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700124 SortedVector <audio_io_handle_t> outputs;
125
François Gaffie11d30102018-11-02 16:09:09 +0100126 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127
Eric Laurente552edb2014-03-10 17:42:56 -0700128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 switch (state)
132 {
133 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100136 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700137 return INVALID_OPERATION;
138 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800139 ALOGV("%s() connecting device %s format %x",
140 __func__, device->toString().c_str(), encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // register new device as available
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800143 index = mAvailableOutputDevices.add(device);
144 if (index >= 0) {
145 sp<HwModule> module = mHwModules.getModuleForDevice(device, encodedFormat);
146 if (module == 0) {
147 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
148 device->toString().c_str());
149 mAvailableOutputDevices.remove(device);
150 return INVALID_OPERATION;
151 }
152 ALOGV("setDeviceConnectionState() module name=%s", module->getName());
153 mAvailableOutputDevices[index]->attach(module);
154 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100160 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200161
François Gaffie11d30102018-11-02 16:09:09 +0100162 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
163 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200164
Francois Gaffie716e1432019-01-14 16:58:59 +0100165 mHwModules.cleanUpForDevice(device);
166
François Gaffie11d30102018-11-02 16:09:09 +0100167 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700168 return INVALID_OPERATION;
169 }
François Gaffie2110e042015-03-24 08:41:51 +0100170 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100171 mEngine->setDeviceConnectionState(device, state);
François Gaffie2110e042015-03-24 08:41:51 +0100172
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700173 // outputs should never be empty here
174 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
175 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100176 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100182 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700183 return INVALID_OPERATION;
184 }
185
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100189 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100192 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
François Gaffie11d30102018-11-02 16:09:09 +0100194 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100195
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800196 // Reset active device codec
197 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
198
François Gaffie2110e042015-03-24 08:41:51 +0100199 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100200 mEngine->setDeviceConnectionState(device, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700201 } break;
202
203 default:
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return BAD_VALUE;
206 }
207
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 checkForDeviceAndOutputChanges([&]() {
209 // outputs must be closed after checkOutputForAllStrategies() is executed
210 if (!outputs.isEmpty()) {
211 for (audio_io_handle_t output : outputs) {
212 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100213 // close unused outputs after device disconnection or direct outputs that have
214 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700215 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
216 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
217 (desc->mDirectOpenCount == 0))) {
218 closeOutput(output);
219 }
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
222 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700224 return false;
225 });
Eric Laurente552edb2014-03-10 17:42:56 -0700226
Eric Laurent87ffa392015-05-22 10:32:38 -0700227 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100228 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
229 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 }
François Gaffie11d30102018-11-02 16:09:09 +0100231 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700232 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
234 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700236 // do not force device change on duplicated output because if device is 0, it will
237 // also force a device 0 for the two outputs it is duplicated to which may override
238 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100239 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100240 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100241 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 // always force when disconnecting (a non-duplicated device)
243 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100244 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700245 }
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
247
Eric Laurentd60560a2015-04-10 11:31:20 -0700248 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100249 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700250 }
251
Eric Laurent72aa32f2014-05-30 18:51:48 -0700252 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700253 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700254 } // end if is output device
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100257 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700258 SortedVector <audio_io_handle_t> inputs;
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 switch (state)
262 {
263 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return INVALID_OPERATION;
268 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800269 sp<HwModule> module = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
270 if (module == NULL) {
271 ALOGW("setDeviceConnectionState(): could not find HW module for device %s",
272 device->toString().c_str());
273 return INVALID_OPERATION;
274 }
275
François Gaffie44481e72016-04-20 07:49:57 +0200276 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
277 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100278 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200279
François Gaffie11d30102018-11-02 16:09:09 +0100280 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
281 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100282
283 mHwModules.cleanUpForDevice(device);
284
Eric Laurentd4692962014-05-05 18:13:44 -0700285 return INVALID_OPERATION;
286 }
287
Francois Gaffie716e1432019-01-14 16:58:59 +0100288 if (mAvailableInputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 return NO_MEMORY;
290 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800291
François Gaffie2110e042015-03-24 08:41:51 +0100292 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100293 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700294 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700295
296 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700297 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100299 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700300 return INVALID_OPERATION;
301 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700302
François Gaffie11d30102018-11-02 16:09:09 +0100303 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700304
305 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100306 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700307
François Gaffie11d30102018-11-02 16:09:09 +0100308 checkInputsForDevice(device, state, inputs);
309 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
François Gaffie2110e042015-03-24 08:41:51 +0100311 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100312 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700313 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700314
315 default:
François Gaffie11d30102018-11-02 16:09:09 +0100316 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700317 return BAD_VALUE;
318 }
319
Eric Laurentd4692962014-05-05 18:13:44 -0700320 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700321 // As the input device list can impact the output device selection, update
322 // getDeviceForStrategy() cache
323 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700324
Eric Laurent87ffa392015-05-22 10:32:38 -0700325 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
327 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 }
329
Eric Laurentd60560a2015-04-10 11:31:20 -0700330 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100331 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700332 }
333
Eric Laurentb52c1522014-05-20 11:27:36 -0700334 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700335 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700336 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700337
François Gaffie11d30102018-11-02 16:09:09 +0100338 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700339 return BAD_VALUE;
340}
341
Eric Laurente0720872014-03-11 09:30:41 -0700342audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100343 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700344{
Eric Laurent634b7142016-04-20 13:48:02 -0700345 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800346 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
347 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700348 (strlen(device_address) != 0)/*matchAddress*/);
349
350 if (devDesc == 0) {
351 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
352 device, device_address);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
354 }
François Gaffie53615e22015-03-19 09:24:12 +0100355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100363 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
Eric Laurent634b7142016-04-20 13:48:02 -0700366
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800367 return (deviceVector->getDevice(
368 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700369 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800370}
371
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800372status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
373 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800374 const char *device_name,
375 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376{
377 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700378 String8 reply;
379 AudioParameter param;
380 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800382 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
383 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800384
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800385 // connect/disconnect only 1 device at a time
386 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Check if the device is currently connected
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800389 DeviceVector availableDevices = getAvailableOutputDevices();
390 DeviceVector deviceList = availableDevices.getDevicesFromTypeMask(device);
391 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800392 // Nothing to do: device is not connected
393 return NO_ERROR;
394 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800395 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800396
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700397 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800398 // configure codecs.
399 // Handle two specific cases by sending a set parameter to
400 // configure A2DP codecs. No need to toggle device state.
401 // Case 1: A2DP active device switches from primary to primary
402 // module
403 // Case 2: A2DP device config changes on primary module.
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700404 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800405 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
406 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
407 if (availablePrimaryOutputDevices().contains(devDesc) &&
408 (module != 0 && module->getHandle() == primaryHandle)) {
409 reply = mpClientInterface->getParameters(
410 AUDIO_IO_HANDLE_NONE,
411 String8(AudioParameter::keyReconfigA2dpSupported));
412 AudioParameter repliedParameters(reply);
413 repliedParameters.getInt(
414 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
415 if (isReconfigA2dpSupported) {
416 const String8 key(AudioParameter::keyReconfigA2dp);
417 param.add(key, String8("true"));
418 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
419 devDesc->setEncodedFormat(encodedFormat);
420 return NO_ERROR;
421 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700422 }
423 }
424
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800425 // Toggle the device state: UNAVAILABLE -> AVAILABLE
426 // This will force reading again the device configuration
427 status = setDeviceConnectionState(device,
428 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800429 device_address, device_name,
430 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 if (status != NO_ERROR) {
432 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
433 status);
434 return status;
435 }
436
437 status = setDeviceConnectionState(device,
438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800439 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800440 if (status != NO_ERROR) {
441 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
442 status);
443 return status;
444 }
445
446 return NO_ERROR;
447}
448
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800449status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
450 std::vector<audio_format_t> *formats)
451{
452 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
453 char *tok = NULL, *saveptr;
454 status_t status = NO_ERROR;
455 char encoding_formats_list[PROPERTY_VALUE_MAX];
456 audio_format_t format = AUDIO_FORMAT_DEFAULT;
457 // FIXME This list should not come from a property but the supported encoded
458 // formats of declared A2DP devices in primary module
459 property_get("persist.bluetooth.a2dp_offload.cap", encoding_formats_list, "");
460 tok = strtok_r(encoding_formats_list, "-", &saveptr);
461 for (;tok != NULL; tok = strtok_r(NULL, "-", &saveptr)) {
462 if (strcmp(tok, "sbc") == 0) {
463 ALOGV("%s: SBC offload supported\n",__func__);
464 format = AUDIO_FORMAT_SBC;
465 } else if (strcmp(tok, "aptx") == 0) {
466 ALOGV("%s: APTX offload supported\n",__func__);
467 format = AUDIO_FORMAT_APTX;
468 } else if (strcmp(tok, "aptxhd") == 0) {
469 ALOGV("%s: APTX HD offload supported\n",__func__);
470 format = AUDIO_FORMAT_APTX_HD;
471 } else if (strcmp(tok, "ldac") == 0) {
472 ALOGV("%s: LDAC offload supported\n",__func__);
473 format = AUDIO_FORMAT_LDAC;
474 } else if (strcmp(tok, "aac") == 0) {
475 ALOGV("%s: AAC offload supported\n",__func__);
476 format = AUDIO_FORMAT_AAC;
477 } else {
478 ALOGE("%s: undefined token - %s\n",__func__, tok);
479 continue;
480 }
481 formats->push_back(format);
482 }
483 return status;
484}
485
François Gaffie11d30102018-11-02 16:09:09 +0100486uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487{
488 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700489 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700490
François Gaffie11d30102018-11-02 16:09:09 +0100491 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700492 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700493 }
François Gaffie11d30102018-11-02 16:09:09 +0100494 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
495
Francois Gaffie716e1432019-01-14 16:58:59 +0100496 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
497 auto txDevice = getDeviceAndMixForAttributes(attr);
François Gaffie11d30102018-11-02 16:09:09 +0100498 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
499 rxDevices.toString().c_str(), txDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700500
501 // release existing RX patch if any
502 if (mCallRxPatch != 0) {
503 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
504 mCallRxPatch.clear();
505 }
506 // release TX patch if any
507 if (mCallTxPatch != 0) {
508 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
509 mCallTxPatch.clear();
510 }
511
512 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
513 // via setOutputDevice() on primary output.
514 // Otherwise, create two audio patches for TX and RX path.
François Gaffie11d30102018-11-02 16:09:09 +0100515 if (availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) {
516 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 // If the TX device is also on the primary HW module, setOutputDevice() will take care
518 // of it due to legacy implementation. If not, create a patch.
François Gaffie11d30102018-11-02 16:09:09 +0100519 if (!availablePrimaryModuleInputDevices().contains(txDevice)) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700520 createTxPatch = true;
521 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700522 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100523 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700524 createTxPatch = true;
525 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700526 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
528 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700529
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800530 return muteWaitMs;
531}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700532
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100534 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700535 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536
François Gaffie11d30102018-11-02 16:09:09 +0100537 if (device == nullptr) {
538 return nullptr;
539 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800540 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100541 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 addSource(mAvailableInputDevices.getDevice(
543 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800544 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100545 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800546 addSink(mAvailableOutputDevices.getDevice(
547 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800548 }
549
François Gaffie11d30102018-11-02 16:09:09 +0100550 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
551 const sp<DeviceDescriptor> outputDevice = isRx ?
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 device : mAvailableOutputDevices.getDevice(
553 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100554 SortedVector<audio_io_handle_t> outputs =
555 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
556 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800557 // request to reuse existing output stream if one is already opened to reach the target device
558 if (output != AUDIO_IO_HANDLE_NONE) {
559 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100560 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
561 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700562 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800563 }
564
565 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700566 // terminate active capture if on the same HW module as the call TX source device
567 // FIXME: would be better to refine to only inputs whose profile connects to the
568 // call TX device but this information is not in the audio patch and logic here must be
569 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800570 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100571 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700572 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700573 }
574 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700575 }
Eric Laurentdc462862016-07-19 12:29:53 -0700576
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800577 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700578 status_t status = mpClientInterface->createAudioPatch(
579 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800580 ALOGW_IF(status != NO_ERROR,
581 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
582 sp<AudioPatch> audioPatch;
583 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700584 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800585 audioPatch->mAfPatchHandle = afPatchHandle;
586 audioPatch->mUid = mUidCached;
587 }
588 return audioPatch;
589}
590
Mikhail Naganovdc769682018-05-04 15:34:08 -0700591sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100592 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700593 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800594 ALOG_ASSERT(!deviceList.isEmpty(),
595 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700596 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700597}
598
Mikhail Naganov100f0122018-11-29 11:22:16 -0800599audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
600 const DeviceVector& devices, const char *moduleId) const {
601 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
602 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
603}
604
605bool AudioPolicyManager::isDeviceOfModule(
606 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
607 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
608 if (module != 0) {
609 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
610 .indexOf(devDesc) != NAME_NOT_FOUND
611 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
612 .indexOf(devDesc) != NAME_NOT_FOUND;
613 }
614 return false;
615}
616
Eric Laurente0720872014-03-11 09:30:41 -0700617void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700618{
619 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100620 // store previous phone state for management of sonification strategy below
621 int oldState = mEngine->getPhoneState();
622
623 if (mEngine->setPhoneState(state) != NO_ERROR) {
624 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700625 return;
626 }
François Gaffie2110e042015-03-24 08:41:51 +0100627 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700628 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700629 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700630 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800631 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700632 }
633
François Gaffie2110e042015-03-24 08:41:51 +0100634 /**
635 * Switching to or from incall state or switching between telephony and VoIP lead to force
636 * routing command.
637 */
638 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
639 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700640
641 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700642 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700643
Eric Laurente552edb2014-03-10 17:42:56 -0700644 int delayMs = 0;
645 if (isStateInCall(state)) {
646 nsecs_t sysTime = systemTime();
647 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700648 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700649 // mute media and sonification strategies and delay device switch by the largest
650 // latency of any output where either strategy is active.
651 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100652 if ((isStrategyActive(desc, STRATEGY_MEDIA,
653 SONIFICATION_HEADSET_MUSIC_DELAY,
654 sysTime) ||
655 isStrategyActive(desc, STRATEGY_SONIFICATION,
656 SONIFICATION_HEADSET_MUSIC_DELAY,
657 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700658 (delayMs < (int)desc->latency()*2)) {
659 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700660 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700661 setStrategyMute(STRATEGY_MEDIA, true, desc);
662 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700663 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700664 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
665 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700666 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
667 }
668 }
669
Eric Laurent87ffa392015-05-22 10:32:38 -0700670 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100671 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700672 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100673 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700674 // force routing command to audio hardware when ending call
675 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100676 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
677 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679
Eric Laurent87ffa392015-05-22 10:32:38 -0700680 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100681 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 } else if (oldState == AUDIO_MODE_IN_CALL) {
683 if (mCallRxPatch != 0) {
684 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
685 mCallRxPatch.clear();
686 }
687 if (mCallTxPatch != 0) {
688 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
689 mCallTxPatch.clear();
690 }
François Gaffie11d30102018-11-02 16:09:09 +0100691 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700692 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100693 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700694 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700696
697 // reevaluate routing on all outputs in case tracks have been started during the call
698 for (size_t i = 0; i < mOutputs.size(); i++) {
699 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100700 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700701 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100702 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700703 }
704 }
705
Eric Laurente552edb2014-03-10 17:42:56 -0700706 if (isStateInCall(state)) {
707 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700708 // force reevaluating accessibility routing when call starts
709 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700710 }
711
712 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700713 if (state == AUDIO_MODE_RINGTONE &&
714 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700715 mLimitRingtoneVolume = true;
716 } else {
717 mLimitRingtoneVolume = false;
718 }
719}
720
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700721audio_mode_t AudioPolicyManager::getPhoneState() {
722 return mEngine->getPhoneState();
723}
724
Eric Laurente0720872014-03-11 09:30:41 -0700725void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100726 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700727{
François Gaffie2110e042015-03-24 08:41:51 +0100728 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700729 if (config == mEngine->getForceUse(usage)) {
730 return;
731 }
Eric Laurente552edb2014-03-10 17:42:56 -0700732
François Gaffie2110e042015-03-24 08:41:51 +0100733 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
734 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
735 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700736 }
François Gaffie2110e042015-03-24 08:41:51 +0100737 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
738 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
739 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700740
741 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700742 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800743
Eric Laurentdc462862016-07-19 12:29:53 -0700744 //FIXME: workaround for truncated touch sounds
745 // to be removed when the problem is handled by system UI
746 uint32_t delayMs = 0;
747 uint32_t waitMs = 0;
748 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
749 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
750 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700751 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100752 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
753 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700754 }
Eric Laurente552edb2014-03-10 17:42:56 -0700755 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700756 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100757 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700758 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100759 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 }
François Gaffie11d30102018-11-02 16:09:09 +0100761 if (forceVolumeReeval && !newDevices.isEmpty()) {
762 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 }
764 }
765
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800766 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100767 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700768 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100769 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800770 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700771 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800772 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700773 }
Eric Laurente552edb2014-03-10 17:42:56 -0700774 }
Eric Laurente552edb2014-03-10 17:42:56 -0700775}
776
Eric Laurente0720872014-03-11 09:30:41 -0700777void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700778{
779 ALOGV("setSystemProperty() property %s, value %s", property, value);
780}
781
Michael Chana94fbb22018-04-24 14:31:19 +1000782// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
783// search to profiles for direct outputs.
784sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100785 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000786 uint32_t samplingRate,
787 audio_format_t format,
788 audio_channel_mask_t channelMask,
789 audio_output_flags_t flags,
790 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700791{
Michael Chana94fbb22018-04-24 14:31:19 +1000792 if (directOnly) {
793 // only retain flags that will drive the direct output profile selection
794 // if explicitly requested
795 static const uint32_t kRelevantFlags =
796 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
797 AUDIO_OUTPUT_FLAG_VOIP_RX);
798 flags =
799 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
800 }
Eric Laurent861a6282015-05-18 15:40:16 -0700801
802 sp<IOProfile> profile;
803
Mikhail Naganovd4120142017-12-06 15:49:22 -0800804 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100806 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700807 samplingRate, NULL /*updatedSamplingRate*/,
808 format, NULL /*updatedFormat*/,
809 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700810 flags)) {
811 continue;
812 }
813 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100814 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700815 continue;
816 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800817 // reject profiles if connected device does not support codec
818 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
819 continue;
820 }
Michael Chana94fbb22018-04-24 14:31:19 +1000821 if (!directOnly) return curProfile;
822 // when searching for direct outputs, if several profiles are compatible, give priority
823 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100824 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700825 continue;
826 }
827 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100828 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700829 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700830 }
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832 }
Eric Laurent861a6282015-05-18 15:40:16 -0700833 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700834}
835
Eric Laurentf4e63452017-11-06 19:31:46 +0000836audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700837{
Eric Laurent3b73df72014-03-11 09:06:29 -0700838 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100839 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800840
841 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
842 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
843 // format, flags, etc. This may result in some discrepancy for functions that utilize
844 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
845 // and AudioSystem::getOutputSamplingRate().
846
François Gaffie11d30102018-11-02 16:09:09 +0100847 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
848 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700849
François Gaffie11d30102018-11-02 16:09:09 +0100850 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
851 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000852 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700853}
854
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700855status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
856 const audio_attributes_t *srcAttr,
857 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700859 if (srcAttr != NULL) {
860 if (!isValidAttributes(srcAttr)) {
861 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
862 __func__,
863 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
864 srcAttr->tags);
865 return BAD_VALUE;
866 }
867 *dstAttr = *srcAttr;
868 } else {
869 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
870 ALOGE("%s: invalid stream type", __func__);
871 return BAD_VALUE;
872 }
873 stream_type_to_audio_attributes(srcStream, dstAttr);
874 }
875 return NO_ERROR;
876}
877
878status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
879 audio_io_handle_t *output,
880 audio_session_t session,
881 const audio_attributes_t *attr,
882 audio_stream_type_t *stream,
883 uid_t uid,
884 const audio_config_t *config,
885 audio_output_flags_t *flags,
886 audio_port_handle_t *selectedDeviceId)
887{
François Gaffie11d30102018-11-02 16:09:09 +0100888 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700889 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100890 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Francois Gaffie716e1432019-01-14 16:58:59 +0100891 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100892 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700893
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700894 status_t status = getAudioAttributes(resultAttr, attr, *stream);
895 if (status != NO_ERROR) {
896 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700897 }
898
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700899 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700900 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700901 __func__,
902 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Francois Gaffie716e1432019-01-14 16:58:59 +0100903 session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700904
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700905 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700906
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700907 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700908
Scott Randolph7b1fd232018-06-18 15:33:03 -0700909 // First check for explicit routing (eg. setPreferredDevice)
Francois Gaffie716e1432019-01-14 16:58:59 +0100910 sp<DeviceDescriptor> requestedDevice = mAvailableOutputDevices.getDeviceFromId(requestedPortId);
911 if (requestedDevice != nullptr) {
912 deviceType = requestedDevice->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700913 } else {
914 // If no explict route, is there a matching dynamic policy that applies?
915 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700916 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700917 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
918 if (!audio_has_proportional_frames(config->format)) {
919 return BAD_VALUE;
920 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700921 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700922 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700923 AudioMix *mix = desc->mPolicyMix;
924 sp<DeviceDescriptor> deviceDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800925 mAvailableOutputDevices.getDevice(
926 mix->mDeviceType, mix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -0700927 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700928 ALOGV("%s returns output %d", __func__, *output);
929 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700930 }
931
932 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700933 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
934 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700935 return BAD_VALUE;
936 }
François Gaffie11d30102018-11-02 16:09:09 +0100937 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700938 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700939
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700940 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200941 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700942 }
943
Nadav Barb2f18162018-07-18 13:01:53 +0300944 // Set incall music only if device was explicitly set, and fallback to the device which is
945 // chosen by the engine if not.
946 // FIXME: provide a more generic approach which is not device specific and move this back
947 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200948 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100949 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300951 audio_is_linear_pcm(config->format) &&
952 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100953 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300954 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
955 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700956 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100957 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300958 }
959 }
960
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700961 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800962 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100963 __func__,
964 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700965
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100966 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100967 if (!msdDevices.isEmpty()) {
968 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800969 sp<DeviceDescriptor> deviceDesc =
970 mAvailableOutputDevices.getDevice(deviceType, String8(), AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +0100971 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
972 ALOGV("%s() Using MSD devices %s instead of device %s",
973 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
974 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100975 } else {
976 *output = AUDIO_IO_HANDLE_NONE;
977 }
978 }
François Gaffie11d30102018-11-02 16:09:09 +0100979 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100980 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +0100981 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100982 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800983 if (*output == AUDIO_IO_HANDLE_NONE) {
984 return INVALID_OPERATION;
985 }
Paul McLeanaa981192015-03-21 09:55:15 -0700986
François Gaffie11d30102018-11-02 16:09:09 +0100987 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700988
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700989 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
990
991 return NO_ERROR;
992}
993
994status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
995 audio_io_handle_t *output,
996 audio_session_t session,
997 audio_stream_type_t *stream,
998 uid_t uid,
999 const audio_config_t *config,
1000 audio_output_flags_t *flags,
1001 audio_port_handle_t *selectedDeviceId,
1002 audio_port_handle_t *portId)
1003{
1004 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1005 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1006 return INVALID_OPERATION;
1007 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001008 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001009 audio_attributes_t resultAttr;
1010 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1011 config, flags, selectedDeviceId);
1012 if (status != NO_ERROR) {
1013 return status;
1014 }
1015
Eric Laurent8fc147b2018-07-22 19:13:55 -07001016 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1017 .format = config->format,
1018 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -07001019 *portId = AudioPort::getNextUniqueId();
1020
Eric Laurent8fc147b2018-07-22 19:13:55 -07001021 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001022 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffie716e1432019-01-14 16:58:59 +01001023 requestedPortId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001024 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -07001025 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001026 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001027 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001028
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001029 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
Francois Gaffie716e1432019-01-14 16:58:59 +01001030 __func__, *output, requestedPortId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001031
Eric Laurente83b55d2014-11-14 10:06:21 -08001032 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001033}
1034
François Gaffie11d30102018-11-02 16:09:09 +01001035audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1036 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001037 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001038 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001039 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +02001040 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001041{
Andy Hungc88b0642018-04-27 15:42:35 -07001042 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001043 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001044
Eric Laurente552edb2014-03-10 17:42:56 -07001045 // open a direct output if required by specified parameters
1046 //force direct flag if offload flag is set: offloading implies a direct output stream
1047 // and all common behaviors are driven by checking only the direct flag
1048 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001049 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1050 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 }
Nadav Bar766fb022018-01-07 12:18:03 +02001052 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1053 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001054 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001055 // only allow deep buffering for music stream type
1056 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001057 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001058 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001059 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001060 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1061 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001062 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001063 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001064 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001065 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001066 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001067 audio_is_linear_pcm(config->format) &&
1068 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001069 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001070 AUDIO_OUTPUT_FLAG_DIRECT);
1071 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001072 }
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Nadav Bar766fb022018-01-07 12:18:03 +02001074
Eric Laurentb732cf52014-09-24 19:08:21 -07001075 sp<IOProfile> profile;
1076
1077 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001078 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001079 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001080 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1081 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001082 goto non_direct_output;
1083 }
1084
Andy Hung2ddee192015-12-18 17:34:44 -08001085 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1086 // This prevents creating an offloaded track and tearing it down immediately after start
1087 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001088 // FIXME: We should check the audio session here but we do not have it in this context.
1089 // This may prevent offloading in rare situations where effects are left active by apps
1090 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001091
Nadav Bar766fb022018-01-07 12:18:03 +02001092 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001093 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001094 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001095 config->sample_rate,
1096 config->format,
1097 config->channel_mask,
1098 (audio_output_flags_t)*flags,
1099 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001100 }
1101
Eric Laurent1c333e22014-05-20 10:48:17 -07001102 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001103 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1104 for (size_t i = 0; i < mOutputs.size(); i++) {
1105 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1106 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1107 // reuse direct output if currently open by the same client
1108 // and configured with same parameters
1109 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001110 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001111 (config->channel_mask == desc->mChannelMask) &&
1112 (session == desc->mDirectClientSession)) {
1113 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001114 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001115 mOutputs.keyAt(i), session);
1116 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001117 }
1118 }
1119 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001120
1121 if (!profile->canOpenNewIo()) {
1122 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001123 }
Eric Laurent861a6282015-05-18 15:40:16 -07001124
Eric Laurent3974e3b2017-12-07 17:58:43 -08001125 sp<SwAudioOutputDescriptor> outputDesc =
1126 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001127
François Gaffie11d30102018-11-02 16:09:09 +01001128 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001129
Dean Wheatley3023b382018-08-09 07:42:40 +10001130 // MSD patch may be using the only output stream that can service this request. Release
1131 // MSD patch to prioritize this request over any active output on MSD.
1132 AudioPatchCollection msdPatches = getMsdPatches();
1133 for (size_t i = 0; i < msdPatches.size(); i++) {
1134 const auto& patch = msdPatches[i];
1135 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1136 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1137 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001138 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001139 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1140 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1141 releaseAudioPatch(patch->mHandle, mUidCached);
1142 break;
1143 }
1144 }
1145 }
1146
François Gaffie11d30102018-11-02 16:09:09 +01001147 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001148
1149 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001150 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001151 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001152 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001153 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001154 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1155 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001156 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1157 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001158 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001159 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001161 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001162 if (audio_is_linear_pcm(config->format) &&
1163 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001164 goto non_direct_output;
1165 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001166 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001167 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001168 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001169 outputDesc->mDirectClientSession = session;
1170
Eric Laurente552edb2014-03-10 17:42:56 -07001171 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001172 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001173 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001174 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001175 return output;
1176 }
1177
Eric Laurentb732cf52014-09-24 19:08:21 -07001178non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001179
1180 // A request for HW A/V sync cannot fallback to a mixed output because time
1181 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001182 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001183 return AUDIO_IO_HANDLE_NONE;
1184 }
1185
Eric Laurente552edb2014-03-10 17:42:56 -07001186 // ignoring channel mask due to downmix capability in mixer
1187
1188 // open a non direct output
1189
1190 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001191 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001192 // get which output is suitable for the specified stream. The actual
1193 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001194 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001195
Eric Laurent8838a382014-09-08 16:44:28 -07001196 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001197 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001198 output = selectOutput(outputs, *flags, config->format,
1199 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001200 }
François Gaffie11d30102018-11-02 16:09:09 +01001201 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001202 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001203 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001204
Eric Laurente552edb2014-03-10 17:42:56 -07001205 return output;
1206}
1207
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001208sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001209 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1210 mAvailableInputDevices);
1211 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1212}
1213
1214DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1215 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1216 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001217}
1218
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001219const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1220 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001221 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1222 if (msdModule != 0) {
1223 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1224 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1225 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1226 const struct audio_port_config *source = &patch->mPatch.sources[j];
1227 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1228 source->ext.device.hw_module == msdModule->getHandle()) {
1229 msdPatches.addAudioPatch(patch->mHandle, patch);
1230 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001231 }
1232 }
1233 }
1234 return msdPatches;
1235}
1236
François Gaffie11d30102018-11-02 16:09:09 +01001237status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001238 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1239{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001240 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001241 if (msdModule == nullptr) {
1242 ALOGE("%s() unable to get MSD module", __func__);
1243 return NO_INIT;
1244 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001245 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001246 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001247 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001248 return NO_INIT;
1249 }
1250 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1251 if (inputProfiles.isEmpty()) {
1252 ALOGE("%s() no input profiles for MSD module", __func__);
1253 return NO_INIT;
1254 }
1255 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1256 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001257 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001258 return NO_INIT;
1259 }
1260 AudioProfileVector msdProfiles;
1261 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1262 for (const auto &inProfile : inputProfiles) {
1263 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1264 msdProfiles.appendVector(inProfile->getAudioProfiles());
1265 }
1266 }
1267 AudioProfileVector deviceProfiles;
1268 for (const auto &outProfile : outputProfiles) {
1269 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1270 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1271 }
1272 }
1273 struct audio_config_base bestSinkConfig;
1274 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1275 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1276 &bestSinkConfig);
1277 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001278 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1279 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001280 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001281 }
1282 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1283 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1284 sinkConfig->format = bestSinkConfig.format;
1285 // For encoded streams force direct flag to prevent downstream mixing.
1286 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1287 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1288 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1289 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1290 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1291 sourceConfig->format = bestSinkConfig.format;
1292 // Copy input stream directly without any processing (e.g. resampling).
1293 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1294 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1295 if (hwAvSync) {
1296 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1297 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1298 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1299 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1300 }
1301 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1302 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1303 sinkConfig->config_mask |= config_mask;
1304 sourceConfig->config_mask |= config_mask;
1305 return NO_ERROR;
1306}
1307
François Gaffie11d30102018-11-02 16:09:09 +01001308PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001309{
1310 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001311 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001312 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1313 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1314 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1315 // For now, we just forcefully try with HwAvSync first.
1316 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1317 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1318 getBestMsdAudioProfileFor(
1319 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1320 if (res == NO_ERROR) {
1321 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1322 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1323 }
1324 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1325 " supporting PCM format conversion.", __func__);
1326 return patchBuilder;
1327}
1328
François Gaffie11d30102018-11-02 16:09:09 +01001329status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1330 sp<DeviceDescriptor> device = outputDevice;
1331 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001332 // Use media strategy for unspecified output device. This should only
1333 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1334 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001335 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1336 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1337 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001338 }
François Gaffie11d30102018-11-02 16:09:09 +01001339 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1340 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001341 const struct audio_patch* patch = patchBuilder.patch();
1342 const AudioPatchCollection msdPatches = getMsdPatches();
1343 if (!msdPatches.isEmpty()) {
1344 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1345 "The current MSD prototype only supports one output patch");
1346 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1347 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1348 return NO_ERROR;
1349 }
1350 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1351 }
1352 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1353 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1354 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1355 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001356 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1357 device->toString().c_str(), patch->sources[0].format,
1358 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001359 return status;
1360}
1361
Eric Laurente0720872014-03-11 09:30:41 -07001362audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001363 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001364 audio_format_t format,
1365 audio_channel_mask_t channelMask,
1366 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001367{
1368 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001369 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001370 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001371 // 1: the output supporting haptic playback when requesting haptic playback
1372 // 2: the output with the highest number of requested policy flags
1373 // 3: the output with the bit depth the closest to the requested one
1374 // 4: the primary output
1375 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001376
1377 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001378 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001379 }
1380 if (outputs.size() == 1) {
1381 return outputs[0];
1382 }
1383
1384 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001385 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1386 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001387 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1388 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1389 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001390 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1391 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001392
Eric Laurente78b6762018-12-19 16:29:01 -08001393 // Flags which must be present on both the request and the selected output
1394 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1395 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1396
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001397 for (audio_io_handle_t output : outputs) {
1398 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001399 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001400 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1401 continue;
1402 }
jiabin40573322018-11-08 12:08:02 -08001403 // If haptic channel is specified, use the haptic output if present.
1404 // When using haptic output, same audio format and sample rate are required.
1405 if (hapticChannelCount > 0) {
1406 // If haptic channel is specified, use the first output that
1407 // support haptic playback.
1408 if (audio_channel_count_from_out_mask(
1409 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1410 && format == outputDesc->mFormat
1411 && samplingRate == outputDesc->mSamplingRate) {
1412 return output;
1413 }
1414 } else {
1415 // When haptic channel is not specified, skip haptic output.
1416 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1417 continue;
1418 }
1419 }
Eric Laurente78b6762018-12-19 16:29:01 -08001420 if ((kMandatedFlags & flags) !=
1421 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1422 continue;
1423 }
jiabin40573322018-11-08 12:08:02 -08001424
Eric Laurent8838a382014-09-08 16:44:28 -07001425 // if a valid format is specified, skip output if not compatible
1426 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001427 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001428 continue;
1429 }
Eric Laurente6930022016-02-11 10:20:40 -08001430 if (AudioPort::isBetterFormatMatch(
1431 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001432 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001433 bestFormat = outputDesc->mFormat;
1434 }
Eric Laurent8838a382014-09-08 16:44:28 -07001435 }
1436
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001437 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001438 if (commonFlags >= maxCommonFlags) {
1439 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001440 if (format != AUDIO_FORMAT_INVALID
1441 && AudioPort::isBetterFormatMatch(
1442 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001443 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001444 bestFormatForFlags = outputDesc->mFormat;
1445 }
1446 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001447 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001448 maxCommonFlags = commonFlags;
1449 bestFormatForFlags = outputDesc->mFormat;
1450 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001451 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001452 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001453 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001454 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
1457 }
1458
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001459 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001460 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001461 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001462 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001463 return outputForFormat;
1464 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001465 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001466 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001467 }
1468
1469 return outputs[0];
1470}
1471
Eric Laurent8fc147b2018-07-22 19:13:55 -07001472status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001473{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001474 ALOGV("%s portId %d", __FUNCTION__, portId);
1475
1476 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1477 if (outputDesc == 0) {
1478 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001479 return BAD_VALUE;
1480 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001481 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001482
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001484 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001485
Eric Laurent733ce942017-12-07 12:18:25 -08001486 status_t status = outputDesc->start();
1487 if (status != NO_ERROR) {
1488 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001489 }
1490
Eric Laurent97ac8712018-07-27 18:59:02 -07001491 uint32_t delayMs;
1492 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001493
1494 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001495 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001496 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001497 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001498 if (delayMs != 0) {
1499 usleep(delayMs * 1000);
1500 }
1501
1502 return status;
1503}
1504
Eric Laurent97ac8712018-07-27 18:59:02 -07001505status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1506 const sp<TrackClientDescriptor>& client,
1507 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001508{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001509 // cannot start playback of STREAM_TTS if any other output is being used
1510 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001511
1512 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001513 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001514 if (stream == AUDIO_STREAM_TTS) {
1515 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001516 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001517 return INVALID_OPERATION;
1518 } else {
1519 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1520 }
1521 } else {
1522 // some playback other than beacon starts
1523 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1524 }
1525
Eric Laurent77305a62016-07-25 16:39:22 -07001526 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001527 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001528 bool force = !outputDesc->isActive() &&
1529 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001530
François Gaffie11d30102018-11-02 16:09:09 +01001531 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001532 AudioMix *policyMix = NULL;
1533 const char *address = NULL;
1534 if (outputDesc->mPolicyMix != NULL) {
1535 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001536 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001537 address = policyMix->mDeviceAddress.string();
1538 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001539 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001540 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001541 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001542 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001543 devices.add(mAvailableOutputDevices.getDevice(newDeviceType,
1544 String8(address), AUDIO_FORMAT_DEFAULT));
Eric Laurent97ac8712018-07-27 18:59:02 -07001545 }
1546
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001547 // requiresMuteCheck is false when we can bypass mute strategy.
1548 // It covers a common case when there is no materially active audio
1549 // and muting would result in unnecessary delay and dropped audio.
1550 const uint32_t outputLatencyMs = outputDesc->latency();
1551 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1552
Eric Laurente552edb2014-03-10 17:42:56 -07001553 // increment usage count for this stream on the requested output:
1554 // NOTE that the usage count is the same for duplicated output and hardware output which is
1555 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001556 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001557
1558 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001559 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1560 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001561 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1562 }
1563 }
Eric Laurente552edb2014-03-10 17:42:56 -07001564
Eric Laurent36829f92017-04-07 19:04:42 -07001565 if (stream == AUDIO_STREAM_MUSIC) {
1566 selectOutputForMusicEffects();
1567 }
1568
François Gaffie11d30102018-11-02 16:09:09 +01001569 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001570 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001571 if (devices.isEmpty()) {
1572 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 }
Eric Laurent36829f92017-04-07 19:04:42 -07001574
Eric Laurente552edb2014-03-10 17:42:56 -07001575 routing_strategy strategy = getStrategy(stream);
1576 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001577 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1578 (beaconMuteLatency > 0);
1579 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001580 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001581 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001582 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001583 // An output has a shared device if
1584 // - managed by the same hw module
1585 // - supports the currently selected device
1586 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001587 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001588
Eric Laurent77305a62016-07-25 16:39:22 -07001589 // force a device change if any other output is:
1590 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001591 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001592 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001593 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001594 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001595 // change the device currently selected by the other output.
1596 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001597 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001598 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001599 force = true;
1600 }
1601 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001602 // a notification so that audio focus effect can propagate, or that a mute/unmute
1603 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001604 const uint32_t latencyMs = desc->latency();
1605 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1606
1607 if (shouldWait && isActive && (waitMs < latencyMs)) {
1608 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001609 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001610
1611 // Require mute check if another output is on a shared device
1612 // and currently active to have proper drain and avoid pops.
1613 // Note restoring AudioTracks onto this output needs to invoke
1614 // a volume ramp if there is no mute.
1615 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001616 }
1617 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001618
1619 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001620 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001621
Eric Laurente552edb2014-03-10 17:42:56 -07001622 // apply volume rules for current stream and device if necessary
1623 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001624 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001625 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001626 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001627
1628 // update the outputs if starting an output with a stream that can affect notification
1629 // routing
1630 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001631
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001632 // force reevaluating accessibility routing when ringtone or alarm starts
1633 if (strategy == STRATEGY_SONIFICATION) {
1634 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1635 }
Eric Laurentdc462862016-07-19 12:29:53 -07001636
1637 if (waitMs > muteWaitMs) {
1638 *delayMs = waitMs - muteWaitMs;
1639 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001640
1641 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1642 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1643 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1644 // change occurs after the MixerThread starts and causes a stream volume
1645 // glitch.
1646 //
1647 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001648 }
Eric Laurentdc462862016-07-19 12:29:53 -07001649
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001650 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1651 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1652 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1653 }
1654
Eric Laurent97ac8712018-07-27 18:59:02 -07001655 // Automatically enable the remote submix input when output is started on a re routing mix
1656 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001657 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001658 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1659 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1661 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001662 "remote-submix",
1663 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001664 }
1665
Eric Laurente552edb2014-03-10 17:42:56 -07001666 return NO_ERROR;
1667}
1668
Eric Laurent8fc147b2018-07-22 19:13:55 -07001669status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001670{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001671 ALOGV("%s portId %d", __FUNCTION__, portId);
1672
1673 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1674 if (outputDesc == 0) {
1675 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001676 return BAD_VALUE;
1677 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001678 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurent97ac8712018-07-27 18:59:02 -07001680 ALOGV("stopOutput() output %d, stream %d, session %d",
1681 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001682
Eric Laurent97ac8712018-07-27 18:59:02 -07001683 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001684
Eric Laurent733ce942017-12-07 12:18:25 -08001685 if (status == NO_ERROR ) {
1686 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001687 }
1688 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001689}
1690
Eric Laurent97ac8712018-07-27 18:59:02 -07001691status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1692 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001693{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001694 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001695 audio_stream_type_t stream = client->stream();
1696
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001697 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1698
Eric Laurent592dd7b2018-08-05 18:58:48 -07001699 if (outputDesc->streamActiveCount(stream) > 0) {
1700 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001701 // Automatically disable the remote submix input when output is stopped on a
1702 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001703 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001704 outputDesc->mPolicyMix != NULL &&
1705 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1706 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1707 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1708 outputDesc->mPolicyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001709 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001710 }
1711 }
1712 bool forceDeviceUpdate = false;
1713 if (client->hasPreferredDevice(true)) {
1714 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1715 forceDeviceUpdate = true;
1716 }
1717
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001719 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001720
Eric Laurente552edb2014-03-10 17:42:56 -07001721 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001722 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001723 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001724 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001725 // delay the device switch by twice the latency because stopOutput() is executed when
1726 // the track stop() command is received and at that time the audio track buffer can
1727 // still contain data that needs to be drained. The latency only covers the audio HAL
1728 // and kernel buffers. Also the latency does not always include additional delay in the
1729 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001730 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001731
1732 // force restoring the device selection on other active outputs if it differs from the
1733 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001734 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001735 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001737 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001738 desc->isActive() &&
1739 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001740 (newDevices != desc->devices())) {
1741 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1742 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001743
François Gaffie11d30102018-11-02 16:09:09 +01001744 setOutputDevices(desc, newDevices2, force, delayMs);
1745
Eric Laurent57de36c2016-09-28 16:59:11 -07001746 // re-apply device specific volume if not done by setOutputDevice()
1747 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001748 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001749 }
Eric Laurente552edb2014-03-10 17:42:56 -07001750 }
1751 }
1752 // update the outputs if stopping one with a stream that can affect notification routing
1753 handleNotificationRoutingForStream(stream);
1754 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001755
1756 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1757 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1758 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1759 }
1760
Eric Laurent36829f92017-04-07 19:04:42 -07001761 if (stream == AUDIO_STREAM_MUSIC) {
1762 selectOutputForMusicEffects();
1763 }
Eric Laurente552edb2014-03-10 17:42:56 -07001764 return NO_ERROR;
1765 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001766 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001767 return INVALID_OPERATION;
1768 }
1769}
1770
Eric Laurent8fc147b2018-07-22 19:13:55 -07001771void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001772{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001773 ALOGV("%s portId %d", __FUNCTION__, portId);
1774
1775 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1776 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001777 // If an output descriptor is closed due to a device routing change,
1778 // then there are race conditions with releaseOutput from tracks
1779 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1780 // destroyed shortly thereafter.
1781 //
1782 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001783 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001784 return;
1785 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001786
1787 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Eric Laurent8fc147b2018-07-22 19:13:55 -07001789 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1790 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001791 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001792 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001793 return;
1794 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001795 if (--outputDesc->mDirectOpenCount == 0) {
1796 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001797 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001798 }
1799 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001800 // stopOutput() needs to be successfully called before releaseOutput()
1801 // otherwise there may be inaccurate stream reference counts.
1802 // This is checked in outputDesc->removeClient below.
1803 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001804}
1805
Eric Laurentcaf7f482014-11-25 17:50:47 -08001806status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1807 audio_io_handle_t *input,
1808 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001809 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001810 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001811 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001812 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001813 input_type_t *inputType,
1814 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001815{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001816 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001817 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001818 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001819
Eric Laurentad2e7b92017-09-14 20:06:42 -07001820 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001821 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001822 audio_attributes_t attributes = *attr;
Eric Laurentc722f302014-12-10 11:21:49 -08001823 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001824 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001825 sp<AudioInputDescriptor> inputDesc;
1826 sp<RecordClientDescriptor> clientDesc;
1827 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001828 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001829
1830 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1831 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1832 return INVALID_OPERATION;
1833 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001834
Francois Gaffie716e1432019-01-14 16:58:59 +01001835 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1836 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001837 }
1838
Paul McLean466dc8e2015-04-17 13:15:36 -06001839 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001840 sp<DeviceDescriptor> explicitRoutingDevice =
1841 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001842
Eric Laurentad2e7b92017-09-14 20:06:42 -07001843 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1844 // possible
1845 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1846 *input != AUDIO_IO_HANDLE_NONE) {
1847 ssize_t index = mInputs.indexOfKey(*input);
1848 if (index < 0) {
1849 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1850 status = BAD_VALUE;
1851 goto error;
1852 }
1853 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001854 RecordClientVector clients = inputDesc->getClientsForSession(session);
1855 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001856 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1857 status = BAD_VALUE;
1858 goto error;
1859 }
1860 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1861 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001862 // corresponds to a new client and is only permitted from the same UID.
1863 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001864 if (clients.size() > 1) {
1865 for (const auto& client : clients) {
1866 // The client map is ordered by key values (portId) and portIds are allocated
1867 // incrementaly. So the first client in this list is the one opened by audio flinger
1868 // when the mmap stream is created and should be ignored as it does not correspond
1869 // to an actual client
1870 if (client == *clients.cbegin()) {
1871 continue;
1872 }
1873 if (uid != client->uid() && !client->isSilenced()) {
1874 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1875 uid, client->portId(), client->uid());
1876 status = INVALID_OPERATION;
1877 goto error;
1878 }
Eric Laurent331679c2018-04-16 17:03:16 -07001879 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001880 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001881 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001882 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001883
Eric Laurent8f42ea12018-08-08 09:08:25 -07001884 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001885 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001886 }
1887
1888 *input = AUDIO_IO_HANDLE_NONE;
1889 *inputType = API_INPUT_INVALID;
1890
Francois Gaffie716e1432019-01-14 16:58:59 +01001891 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001892
Francois Gaffie716e1432019-01-14 16:58:59 +01001893 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1894 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1895 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001896 if (status != NO_ERROR) {
1897 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001898 }
1899 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001900 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001901 String8(attr->tags + strlen("addr=")),
1902 AUDIO_FORMAT_DEFAULT);
Eric Laurent275e8e92014-11-30 15:14:47 -08001903 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001904 if (explicitRoutingDevice != nullptr) {
1905 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001906 } else {
Francois Gaffie716e1432019-01-14 16:58:59 +01001907 device = getDeviceAndMixForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07001908 }
François Gaffie11d30102018-11-02 16:09:09 +01001909 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001910 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001911 status = BAD_VALUE;
1912 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001913 }
François Gaffie11d30102018-11-02 16:09:09 +01001914 if (policyMix != nullptr) {
1915 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1916 // there is an external policy, but this input is attached to a mix of recorders,
1917 // meaning it receives audio injected into the framework, so the recorder doesn't
1918 // know about it and is therefore considered "legacy"
1919 *inputType = API_INPUT_LEGACY;
1920 } else if (audio_is_remote_submix_device(device->type())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001921 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"),
1922 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001923 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001924 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001925 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001926 } else {
1927 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001928 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001929
Eric Laurent599c7582015-12-07 18:05:55 -08001930 }
1931
Francois Gaffie716e1432019-01-14 16:58:59 +01001932 *input = getInputForDevice(device, session, attributes.source,
Eric Laurentfe231122017-11-17 17:48:06 -08001933 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001934 policyMix);
1935 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001936 status = INVALID_OPERATION;
1937 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001938 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001939
Eric Laurent8f42ea12018-08-08 09:08:25 -07001940exit:
1941
François Gaffie11d30102018-11-02 16:09:09 +01001942 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1943 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001944
Francois Gaffie716e1432019-01-14 16:58:59 +01001945 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07001946 mSoundTriggerSessions.indexOfKey(session) > 0;
1947 *portId = AudioPort::getNextUniqueId();
1948
François Gaffie11d30102018-11-02 16:09:09 +01001949 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01001950 requestedDeviceId, attributes.source, flags,
1951 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001952 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001953 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001954
1955 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1956 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001957
Eric Laurent599c7582015-12-07 18:05:55 -08001958 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001959
1960error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001961 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001962}
1963
1964
François Gaffie11d30102018-11-02 16:09:09 +01001965audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001966 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001967 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001968 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001969 audio_input_flags_t flags,
1970 AudioMix *policyMix)
1971{
1972 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1973 audio_source_t halInputSource = inputSource;
1974 bool isSoundTrigger = false;
1975
1976 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1977 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1978 if (index >= 0) {
1979 input = mSoundTriggerSessions.valueFor(session);
1980 isSoundTrigger = true;
1981 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1982 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1983 } else {
1984 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001985 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001986 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001987 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001988 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001989 }
1990
Andy Hungf129b032015-04-07 13:45:50 -07001991 // find a compatible input profile (not necessarily identical in parameters)
1992 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001993 // sampling rate and flags may be updated by getInputProfile
1994 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1995 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001996 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001997 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001998 audio_input_flags_t profileFlags = flags;
1999 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002000 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002001 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002002 profileFlags);
2003 if (profile != 0) {
2004 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002005 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2006 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002007 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2008 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2009 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002010 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2011 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2012 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002013 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002014 }
Eric Laurente552edb2014-03-10 17:42:56 -07002015 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002016 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002017 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002018 if (samplingRate == 0) {
2019 samplingRate = profileSamplingRate;
2020 }
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurent322b4d22015-04-03 15:57:54 -07002022 if (profile->getModuleHandle() == 0) {
2023 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002024 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002025 }
2026
Eric Laurent3974e3b2017-12-07 17:58:43 -08002027 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002028 for (size_t i = 0; i < mInputs.size(); ) {
2029 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2030 if (desc->mProfile != profile) {
2031 continue;
2032 }
2033 // if sound trigger, reuse input if used by other sound trigger on same session
2034 // else
2035 // reuse input if active client app is not in IDLE state
2036 //
2037 RecordClientVector clients = desc->clientsList();
2038 bool doClose = false;
2039 for (const auto& client : clients) {
2040 if (isSoundTrigger != client->isSoundTrigger()) {
2041 continue;
2042 }
2043 if (client->isSoundTrigger()) {
2044 if (session == client->session()) {
2045 return desc->mIoHandle;
2046 }
2047 continue;
2048 }
2049 if (client->active() && client->appState() != APP_STATE_IDLE) {
2050 return desc->mIoHandle;
2051 }
2052 doClose = true;
2053 }
2054 if (doClose) {
2055 closeInput(desc->mIoHandle);
2056 } else {
2057 i++;
2058 }
2059 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002060 }
2061
Eric Laurentfe231122017-11-17 17:48:06 -08002062 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002063
Eric Laurentfe231122017-11-17 17:48:06 -08002064 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2065 lConfig.sample_rate = profileSamplingRate;
2066 lConfig.channel_mask = profileChannelMask;
2067 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002068
François Gaffie11d30102018-11-02 16:09:09 +01002069 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002070
2071 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002072 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002073 (profileSamplingRate != lConfig.sample_rate) ||
2074 !audio_formats_match(profileFormat, lConfig.format) ||
2075 (profileChannelMask != lConfig.channel_mask)) {
2076 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002077 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002078 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002079 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002080 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002081 }
Eric Laurent599c7582015-12-07 18:05:55 -08002082 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084
Eric Laurentc722f302014-12-10 11:21:49 -08002085 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002086
Eric Laurent599c7582015-12-07 18:05:55 -08002087 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002088 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002089
Eric Laurent599c7582015-12-07 18:05:55 -08002090 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002091}
2092
Eric Laurent4eb58f12018-12-07 16:41:02 -08002093status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 ALOGV("%s portId %d", __FUNCTION__, portId);
2096
2097 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2098 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002099 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100 return BAD_VALUE;
2101 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002103 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002104 if (client->active()) {
2105 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2106 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002107 }
2108
Eric Laurent8f42ea12018-08-08 09:08:25 -07002109 audio_session_t session = client->session();
2110
Eric Laurent4eb58f12018-12-07 16:41:02 -08002111 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112
Eric Laurent4eb58f12018-12-07 16:41:02 -08002113 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002114
Eric Laurent4eb58f12018-12-07 16:41:02 -08002115 status_t status = inputDesc->start();
2116 if (status != NO_ERROR) {
2117 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002118 }
Eric Laurente552edb2014-03-10 17:42:56 -07002119
Eric Laurent4eb58f12018-12-07 16:41:02 -08002120 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002121 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002123
Eric Laurent8f42ea12018-08-08 09:08:25 -07002124 // indicate active capture to sound trigger service if starting capture from a mic on
2125 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002126 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002127 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002128
Eric Laurent8f42ea12018-08-08 09:08:25 -07002129 if (inputDesc->activeCount() == 1) {
2130 // if input maps to a dynamic policy with an activity listener, notify of state change
2131 if ((inputDesc->mPolicyMix != NULL)
2132 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2133 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2134 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002135 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002136
François Gaffie11d30102018-11-02 16:09:09 +01002137 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2138 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002139 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2140 SoundTrigger::setCaptureState(true);
2141 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002142
Eric Laurent8f42ea12018-08-08 09:08:25 -07002143 // automatically enable the remote submix output when input is started if not
2144 // used by a policy mix of type MIX_TYPE_RECORDERS
2145 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002146 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 String8 address = String8("");
2148 if (inputDesc->mPolicyMix == NULL) {
2149 address = String8("0");
2150 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2151 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002152 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 if (address != "") {
2154 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2155 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002156 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002157 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002158 }
Eric Laurente552edb2014-03-10 17:42:56 -07002159 }
2160
Eric Laurent8f42ea12018-08-08 09:08:25 -07002161 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurente552edb2014-03-10 17:42:56 -07002163 return NO_ERROR;
2164}
2165
Eric Laurent8fc147b2018-07-22 19:13:55 -07002166status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002167{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168 ALOGV("%s portId %d", __FUNCTION__, portId);
2169
2170 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2171 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002173 return BAD_VALUE;
2174 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002175 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002176 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002177 if (!client->active()) {
2178 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002179 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002180 }
2181
Eric Laurent8f42ea12018-08-08 09:08:25 -07002182 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002183
Eric Laurent8f42ea12018-08-08 09:08:25 -07002184 inputDesc->stop();
2185 if (inputDesc->isActive()) {
2186 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2187 } else {
2188 // if input maps to a dynamic policy with an activity listener, notify of state change
2189 if ((inputDesc->mPolicyMix != NULL)
2190 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2191 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2192 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002193 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002194
2195 // automatically disable the remote submix output when input is stopped if not
2196 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002197 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002198 String8 address = String8("");
2199 if (inputDesc->mPolicyMix == NULL) {
2200 address = String8("0");
2201 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2202 address = inputDesc->mPolicyMix->mDeviceAddress;
2203 }
2204 if (address != "") {
2205 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2206 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002207 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 }
2209 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 resetInputDevice(input);
2211
2212 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2213 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002214 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2215 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2217 SoundTrigger::setCaptureState(false);
2218 }
2219 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002220 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002221 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002222}
2223
Eric Laurent8fc147b2018-07-22 19:13:55 -07002224void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002225{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226 ALOGV("%s portId %d", __FUNCTION__, portId);
2227
2228 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2229 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002231 return;
2232 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002233 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234 audio_io_handle_t input = inputDesc->mIoHandle;
2235
Eric Laurent8f42ea12018-08-08 09:08:25 -07002236 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002237
Andy Hung39efb7a2018-09-26 15:39:28 -07002238 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002239
Andy Hung39efb7a2018-09-26 15:39:28 -07002240 if (inputDesc->getClientCount() > 0) {
2241 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002242 return;
2243 }
2244
Eric Laurent05b90f82014-08-27 15:32:29 -07002245 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002246 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002247 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002248}
2249
Eric Laurent8f42ea12018-08-08 09:08:25 -07002250void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002251{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002252 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253
2254 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002255 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002256 }
2257}
2258
Eric Laurent8f42ea12018-08-08 09:08:25 -07002259void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2260{
2261 stopInput(portId);
2262 releaseInput(portId);
2263}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264
Eric Laurentd4692962014-05-05 18:13:44 -07002265void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002266 bool patchRemoved = false;
2267
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002268 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002269 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002270 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002271 if (patch_index >= 0) {
2272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002273 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002274 mAudioPatches.removeItemsAt(patch_index);
2275 patchRemoved = true;
2276 }
Eric Laurentfe231122017-11-17 17:48:06 -08002277 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002278 }
2279 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002280 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002281 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002282
2283 if (patchRemoved) {
2284 mpClientInterface->onAudioPatchListUpdate();
2285 }
Eric Laurentd4692962014-05-05 18:13:44 -07002286}
2287
Eric Laurente0720872014-03-11 09:30:41 -07002288void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002289 int indexMin,
2290 int indexMax)
2291{
2292 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002293 if (indexMin < 0 || indexMax < 0) {
2294 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2295 return;
2296 }
François Gaffied1ab2bd2015-12-02 18:20:06 +01002297 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002298
2299 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002300 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2301 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002302 continue;
2303 }
2304 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002305 }
Eric Laurente552edb2014-03-10 17:42:56 -07002306}
2307
Eric Laurente0720872014-03-11 09:30:41 -07002308status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002309 int index,
2310 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002311{
2312
Nadav Bar7c605f62017-12-25 00:01:52 +02002313 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2314 // app that has MODIFY_PHONE_STATE permission.
2315 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2316 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002317 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002318 return BAD_VALUE;
2319 }
2320 if (!audio_is_output_device(device)) {
2321 return BAD_VALUE;
2322 }
2323
2324 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002325 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002326
Eric Laurent1fd372e2016-04-06 14:23:53 -07002327 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002328 stream, device, index);
2329
Eric Laurent28d09f02016-03-08 10:43:05 -08002330 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002331 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2332 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002333 continue;
2334 }
2335 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2336 }
Eric Laurente552edb2014-03-10 17:42:56 -07002337
Eric Laurent1fd372e2016-04-06 14:23:53 -07002338 // update volume on all outputs and streams matching the following:
2339 // - The requested stream (or a stream matching for volume control) is active on the output
2340 // - The device (or devices) selected by the strategy corresponding to this stream includes
2341 // the requested device
2342 // - For non default requested device, currently selected device on the output is either the
2343 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002344 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2345 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002346 status_t status = NO_ERROR;
2347 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002348 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002349 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002350 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002351 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002352 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002353 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002354 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002355 continue;
2356 }
Eric Laurent794fde22016-03-11 09:50:45 -08002357 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002358 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2359 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002360 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2361 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002362 continue;
2363 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002364 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002365 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002366 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002367 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002368 } else {
2369 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002370 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002371 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002372 // rescale index before applying to curStream as ranges may be different for
2373 // stream and curStream
2374 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002375 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002376 //FIXME: workaround for truncated touch sounds
2377 // delayed volume change for system stream to be removed when the problem is
2378 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002379 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002380 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002381 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002382 if (volStatus != NO_ERROR) {
2383 status = volStatus;
2384 }
2385 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002386 }
Eric Laurente552edb2014-03-10 17:42:56 -07002387 }
2388 return status;
2389}
2390
Eric Laurente0720872014-03-11 09:30:41 -07002391status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002392 int *index,
2393 audio_devices_t device)
2394{
2395 if (index == NULL) {
2396 return BAD_VALUE;
2397 }
2398 if (!audio_is_output_device(device)) {
2399 return BAD_VALUE;
2400 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002401 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002402 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002403 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002404 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2405 }
François Gaffiedfd74092015-03-19 12:10:59 +01002406 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002407
François Gaffied1ab2bd2015-12-02 18:20:06 +01002408 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002409 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2410 return NO_ERROR;
2411}
2412
Eric Laurent36829f92017-04-07 19:04:42 -07002413audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002414{
2415 // select one output among several suitable for global effects.
2416 // The priority is as follows:
2417 // 1: An offloaded output. If the effect ends up not being offloadable,
2418 // AudioFlinger will invalidate the track and the offloaded output
2419 // will be closed causing the effect to be moved to a PCM output.
2420 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002421 // 3: The primary output
2422 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002423
Eric Laurent3b73df72014-03-11 09:06:29 -07002424 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002425 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2426 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002427
Eric Laurent36829f92017-04-07 19:04:42 -07002428 if (outputs.size() == 0) {
2429 return AUDIO_IO_HANDLE_NONE;
2430 }
Eric Laurente552edb2014-03-10 17:42:56 -07002431
Eric Laurent36829f92017-04-07 19:04:42 -07002432 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2433 bool activeOnly = true;
2434
2435 while (output == AUDIO_IO_HANDLE_NONE) {
2436 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2437 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2438 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2439
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002440 for (audio_io_handle_t output : outputs) {
2441 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002442 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2443 continue;
2444 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002445 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2446 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002447 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002448 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002449 }
2450 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002451 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002452 }
2453 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002454 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002455 }
2456 }
2457 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2458 output = outputOffloaded;
2459 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2460 output = outputDeepBuffer;
2461 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2462 output = outputPrimary;
2463 } else {
2464 output = outputs[0];
2465 }
2466 activeOnly = false;
2467 }
2468
2469 if (output != mMusicEffectOutput) {
2470 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2471 mMusicEffectOutput = output;
2472 }
2473
2474 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002475 return output;
2476}
2477
Eric Laurent36829f92017-04-07 19:04:42 -07002478audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2479{
2480 return selectOutputForMusicEffects();
2481}
2482
Eric Laurente0720872014-03-11 09:30:41 -07002483status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002484 audio_io_handle_t io,
2485 uint32_t strategy,
2486 int session,
2487 int id)
2488{
2489 ssize_t index = mOutputs.indexOfKey(io);
2490 if (index < 0) {
2491 index = mInputs.indexOfKey(io);
2492 if (index < 0) {
2493 ALOGW("registerEffect() unknown io %d", io);
2494 return INVALID_OPERATION;
2495 }
2496 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002497 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002498}
2499
Eric Laurentc241b0d2018-11-28 09:08:49 -08002500status_t AudioPolicyManager::unregisterEffect(int id)
2501{
2502 if (mEffects.getEffect(id) == nullptr) {
2503 return INVALID_OPERATION;
2504 }
2505
2506 if (mEffects.isEffectEnabled(id)) {
2507 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2508 setEffectEnabled(id, false);
2509 }
2510 return mEffects.unregisterEffect(id);
2511}
2512
2513status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2514{
2515 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2516 if (effect == nullptr) {
2517 return INVALID_OPERATION;
2518 }
2519
2520 status_t status = mEffects.setEffectEnabled(id, enabled);
2521 if (status == NO_ERROR) {
2522 mInputs.trackEffectEnabled(effect, enabled);
2523 }
2524 return status;
2525}
2526
Eric Laurentc75307b2015-03-17 15:29:32 -07002527bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2528{
Eric Laurent28d09f02016-03-08 10:43:05 -08002529 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002530 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2531 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002532 continue;
2533 }
2534 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2535 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002536 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002537}
2538
2539bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2540{
2541 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2542}
2543
Eric Laurente0720872014-03-11 09:30:41 -07002544bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002545{
2546 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002547 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002548 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002549 return true;
2550 }
2551 }
2552 return false;
2553}
2554
Eric Laurent275e8e92014-11-30 15:14:47 -08002555// Register a list of custom mixes with their attributes and format.
2556// When a mix is registered, corresponding input and output profiles are
2557// added to the remote submix hw module. The profile contains only the
2558// parameters (sampling rate, format...) specified by the mix.
2559// The corresponding input remote submix device is also connected.
2560//
2561// When a remote submix device is connected, the address is checked to select the
2562// appropriate profile and the corresponding input or output stream is opened.
2563//
2564// When capture starts, getInputForAttr() will:
2565// - 1 look for a mix matching the address passed in attribtutes tags if any
2566// - 2 if none found, getDeviceForInputSource() will:
2567// - 2.1 look for a mix matching the attributes source
2568// - 2.2 if none found, default to device selection by policy rules
2569// At this time, the corresponding output remote submix device is also connected
2570// and active playback use cases can be transferred to this mix if needed when reconnecting
2571// after AudioTracks are invalidated
2572//
2573// When playback starts, getOutputForAttr() will:
2574// - 1 look for a mix matching the address passed in attribtutes tags if any
2575// - 2 if none found, look for a mix matching the attributes usage
2576// - 3 if none found, default to device and output selection by policy rules.
2577
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002578status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002579{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002580 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2581 status_t res = NO_ERROR;
2582
2583 sp<HwModule> rSubmixModule;
2584 // examine each mix's route type
2585 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002588 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002590 break;
2591 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002592 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002593 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002595 rSubmixModule = mHwModules.getModuleFromName(
2596 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2597 if (rSubmixModule == 0) {
2598 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2599 i);
2600 res = INVALID_OPERATION;
2601 break;
2602 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002604
Eric Laurent97ac8712018-07-27 18:59:02 -07002605 String8 address = mix.mDeviceAddress;
2606 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2607 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2608 } else {
2609 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2610 }
François Gaffie036e1e92015-03-19 10:16:24 +01002611
Eric Laurent97ac8712018-07-27 18:59:02 -07002612 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002613 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002614 res = INVALID_OPERATION;
2615 break;
2616 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002617 audio_config_t outputConfig = mix.mFormat;
2618 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002619 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2620 // stereo and let audio flinger do the channel conversion if needed.
2621 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2622 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2623 rSubmixModule->addOutputProfile(address, &outputConfig,
2624 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2625 rSubmixModule->addInputProfile(address, &inputConfig,
2626 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002627
Eric Laurent97ac8712018-07-27 18:59:02 -07002628 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002629 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2630 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002631 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 } else {
2633 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2634 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002635 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002637 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2638 String8 address = mix.mDeviceAddress;
2639 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002640 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2641 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002643 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002644 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2645 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2646 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2647 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2648 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2649 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002650 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2651 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002652 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002653 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002654 } else {
2655 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002656 }
2657 break;
2658 }
2659 }
2660
2661 if (res != NO_ERROR) {
2662 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002663 i, device, address.string());
2664 res = INVALID_OPERATION;
2665 break;
2666 } else if (!foundOutput) {
2667 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2668 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002669 res = INVALID_OPERATION;
2670 break;
2671 }
Eric Laurentc722f302014-12-10 11:21:49 -08002672 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002673 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002674 if (res != NO_ERROR) {
2675 unregisterPolicyMixes(mixes);
2676 }
2677 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002678}
2679
2680status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2681{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002682 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002683 status_t res = NO_ERROR;
2684 sp<HwModule> rSubmixModule;
2685 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002686 for (const auto& mix : mixes) {
2687 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002688
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002689 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002690 rSubmixModule = mHwModules.getModuleFromName(
2691 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2692 if (rSubmixModule == 0) {
2693 res = INVALID_OPERATION;
2694 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002695 }
2696 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002697
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002698 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002699
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002700 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2701 res = INVALID_OPERATION;
2702 continue;
2703 }
2704
2705 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2706 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2707 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2708 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002709 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002710 }
2711 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2712 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2713 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2714 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002715 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002716 }
2717 rSubmixModule->removeOutputProfile(address);
2718 rSubmixModule->removeInputProfile(address);
2719
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002720 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2721 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002722 res = INVALID_OPERATION;
2723 continue;
2724 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002725 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002726 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002727 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002728}
2729
Mikhail Naganov100f0122018-11-29 11:22:16 -08002730void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2731{
2732 size_t i = 0;
2733 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2734 for (const auto& fmt : mManualSurroundFormats) {
2735 if (i++ != 0) dst->append(", ");
2736 std::string sfmt;
2737 FormatConverter::toString(fmt, sfmt);
2738 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2739 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2740 }
2741}
2742
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002743status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2744 const Vector<AudioDeviceTypeAddr>& devices) {
2745 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2746 // uid/device affinity is only for output devices
2747 for (size_t i = 0; i < devices.size(); i++) {
2748 if (!audio_is_output_device(devices[i].mType)) {
2749 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2750 devices[i].mType);
2751 return BAD_VALUE;
2752 }
2753 }
2754 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2755 if (res == NO_ERROR) {
2756 // reevaluate outputs for all given devices
2757 for (size_t i = 0; i < devices.size(); i++) {
2758 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002759 devices[i].mType, devices[i].mAddress, String8(),
2760 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002761 SortedVector<audio_io_handle_t> outputs;
2762 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002763 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002764 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2765 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2766 return INVALID_OPERATION;
2767 }
2768 }
2769 }
2770 return res;
2771}
2772
2773status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2774 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2775 Vector<AudioDeviceTypeAddr> devices;
2776 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2777 if (res == NO_ERROR) {
2778 // reevaluate outputs for all found devices
2779 for (size_t i = 0; i < devices.size(); i++) {
2780 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002781 devices[i].mType, devices[i].mAddress, String8(),
2782 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002783 SortedVector<audio_io_handle_t> outputs;
2784 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002785 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002786 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2787 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2788 return INVALID_OPERATION;
2789 }
2790 }
2791 }
2792
2793 return res;
2794}
2795
Andy Hungc29d82b2018-10-05 12:23:17 -07002796void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002797{
Andy Hungc29d82b2018-10-05 12:23:17 -07002798 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2799 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002800 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002801 std::string stateLiteral;
2802 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002803 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002804 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2805 "communications", "media", "record", "dock", "system",
2806 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2807 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2808 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002809 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2810 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2811 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2812 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2813 dst->append(" (MANUAL: ");
2814 dumpManualSurroundFormats(dst);
2815 dst->append(")");
2816 }
2817 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002818 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002819 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2820 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2821 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2822 mAvailableOutputDevices.dump(dst, String8("Available output"));
2823 mAvailableInputDevices.dump(dst, String8("Available input"));
2824 mHwModulesAll.dump(dst);
2825 mOutputs.dump(dst);
2826 mInputs.dump(dst);
2827 mVolumeCurves->dump(dst);
2828 mEffects.dump(dst);
2829 mAudioPatches.dump(dst);
2830 mPolicyMixes.dump(dst);
2831 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002832}
2833
2834status_t AudioPolicyManager::dump(int fd)
2835{
2836 String8 result;
2837 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002838 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002839 return NO_ERROR;
2840}
2841
2842// This function checks for the parameters which can be offloaded.
2843// This can be enhanced depending on the capability of the DSP and policy
2844// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002845bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002846{
2847 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002848 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002849 offloadInfo.sample_rate, offloadInfo.channel_mask,
2850 offloadInfo.format,
2851 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2852 offloadInfo.has_video);
2853
Andy Hung2ddee192015-12-18 17:34:44 -08002854 if (mMasterMono) {
2855 return false; // no offloading if mono is set.
2856 }
2857
Eric Laurente552edb2014-03-10 17:42:56 -07002858 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002859 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2860 ALOGV("offload disabled by audio.offload.disable");
2861 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002862 }
2863
2864 // Check if stream type is music, then only allow offload as of now.
2865 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2866 {
2867 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2868 return false;
2869 }
2870
2871 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002872 const bool allowOffloadWithVideo =
2873 property_get_bool("audio.offload.video", false /* default_value */);
2874 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002875 ALOGV("isOffloadSupported: has_video == true, returning false");
2876 return false;
2877 }
2878
2879 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002880 const int min_duration_secs = property_get_int32(
2881 "audio.offload.min.duration.secs", -1 /* default_value */);
2882 if (min_duration_secs >= 0) {
2883 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2884 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2885 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002886 return false;
2887 }
2888 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2889 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2890 return false;
2891 }
2892
2893 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2894 // creating an offloaded track and tearing it down immediately after start when audioflinger
2895 // detects there is an active non offloadable effect.
2896 // FIXME: We should check the audio session here but we do not have it in this context.
2897 // This may prevent offloading in rare situations where effects are left active by apps
2898 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002899 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002900 return false;
2901 }
2902
2903 // See if there is a profile to support this.
2904 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002905 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002906 offloadInfo.sample_rate,
2907 offloadInfo.format,
2908 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002909 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2910 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002911 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2912 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002913}
2914
Michael Chana94fbb22018-04-24 14:31:19 +10002915bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2916 const audio_attributes_t& attributes) {
2917 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2918 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002919 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002920 config.sample_rate,
2921 config.format,
2922 config.channel_mask,
2923 output_flags,
2924 true /* directOnly */);
2925 ALOGV("%s() profile %sfound with name: %s, "
2926 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2927 __FUNCTION__, profile != 0 ? "" : "NOT ",
2928 (profile != 0 ? profile->getTagName().string() : "null"),
2929 config.sample_rate, config.format, config.channel_mask, output_flags);
2930 return (profile != 0);
2931}
2932
Eric Laurent6a94d692014-05-20 11:18:06 -07002933status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2934 audio_port_type_t type,
2935 unsigned int *num_ports,
2936 struct audio_port *ports,
2937 unsigned int *generation)
2938{
2939 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2940 generation == NULL) {
2941 return BAD_VALUE;
2942 }
2943 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2944 if (ports == NULL) {
2945 *num_ports = 0;
2946 }
2947
2948 size_t portsWritten = 0;
2949 size_t portsMax = *num_ports;
2950 *num_ports = 0;
2951 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002952 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2953 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002955 for (const auto& dev : mAvailableOutputDevices) {
2956 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002957 continue;
2958 }
2959 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002960 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002961 }
2962 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002963 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 }
2965 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002966 for (const auto& dev : mAvailableInputDevices) {
2967 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002968 continue;
2969 }
2970 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002971 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002972 }
2973 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 }
2976 }
2977 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2978 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2979 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2980 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2981 }
2982 *num_ports += mInputs.size();
2983 }
2984 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002985 size_t numOutputs = 0;
2986 for (size_t i = 0; i < mOutputs.size(); i++) {
2987 if (!mOutputs[i]->isDuplicated()) {
2988 numOutputs++;
2989 if (portsWritten < portsMax) {
2990 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2991 }
2992 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002993 }
Eric Laurent84c70242014-06-23 08:46:27 -07002994 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 }
2996 }
2997 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002998 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002999 return NO_ERROR;
3000}
3001
Eric Laurent99fcae42018-05-17 16:59:18 -07003002status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003003{
Eric Laurent99fcae42018-05-17 16:59:18 -07003004 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3005 return BAD_VALUE;
3006 }
3007 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3008 if (dev != 0) {
3009 dev->toAudioPort(port);
3010 return NO_ERROR;
3011 }
3012 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3013 if (dev != 0) {
3014 dev->toAudioPort(port);
3015 return NO_ERROR;
3016 }
3017 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3018 if (out != 0) {
3019 out->toAudioPort(port);
3020 return NO_ERROR;
3021 }
3022 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3023 if (in != 0) {
3024 in->toAudioPort(port);
3025 return NO_ERROR;
3026 }
3027 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003028}
3029
Eric Laurent6a94d692014-05-20 11:18:06 -07003030status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3031 audio_patch_handle_t *handle,
3032 uid_t uid)
3033{
3034 ALOGV("createAudioPatch()");
3035
3036 if (handle == NULL || patch == NULL) {
3037 return BAD_VALUE;
3038 }
3039 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3040
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003041 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003042 return BAD_VALUE;
3043 }
3044 // only one source per audio patch supported for now
3045 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 return INVALID_OPERATION;
3047 }
Eric Laurent874c42872014-08-08 15:13:39 -07003048
3049 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 return INVALID_OPERATION;
3051 }
Eric Laurent874c42872014-08-08 15:13:39 -07003052 for (size_t i = 0; i < patch->num_sinks; i++) {
3053 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3054 return INVALID_OPERATION;
3055 }
3056 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003057
3058 sp<AudioPatch> patchDesc;
3059 ssize_t index = mAudioPatches.indexOfKey(*handle);
3060
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3062 patch->sources[0].role,
3063 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003064#if LOG_NDEBUG == 0
3065 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08003066 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07003067 patch->sinks[i].role,
3068 patch->sinks[i].type);
3069 }
3070#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003071
3072 if (index >= 0) {
3073 patchDesc = mAudioPatches.valueAt(index);
3074 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3075 mUidCached, patchDesc->mUid, uid);
3076 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3077 return INVALID_OPERATION;
3078 }
3079 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003080 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003081 }
3082
3083 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003084 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 if (outputDesc == NULL) {
3086 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3087 return BAD_VALUE;
3088 }
Eric Laurent84c70242014-06-23 08:46:27 -07003089 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3090 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 if (patchDesc != 0) {
3092 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3093 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3094 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3095 return BAD_VALUE;
3096 }
3097 }
Eric Laurent874c42872014-08-08 15:13:39 -07003098 DeviceVector devices;
3099 for (size_t i = 0; i < patch->num_sinks; i++) {
3100 // Only support mix to devices connection
3101 // TODO add support for mix to mix connection
3102 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3103 ALOGV("createAudioPatch() source mix but sink is not a device");
3104 return INVALID_OPERATION;
3105 }
3106 sp<DeviceDescriptor> devDesc =
3107 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3108 if (devDesc == 0) {
3109 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3110 return BAD_VALUE;
3111 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003112
François Gaffie11d30102018-11-02 16:09:09 +01003113 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003114 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003115 NULL, // updatedSamplingRate
3116 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003117 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003118 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003119 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003120 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003121 ALOGV("createAudioPatch() profile not supported for device %08x",
3122 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003123 return INVALID_OPERATION;
3124 }
3125 devices.add(devDesc);
3126 }
3127 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003128 return INVALID_OPERATION;
3129 }
Eric Laurent874c42872014-08-08 15:13:39 -07003130
Eric Laurent6a94d692014-05-20 11:18:06 -07003131 // TODO: reconfigure output format and channels here
3132 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003133 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003134 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 index = mAudioPatches.indexOfKey(*handle);
3136 if (index >= 0) {
3137 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3138 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3139 }
3140 patchDesc = mAudioPatches.valueAt(index);
3141 patchDesc->mUid = uid;
3142 ALOGV("createAudioPatch() success");
3143 } else {
3144 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3145 return INVALID_OPERATION;
3146 }
3147 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3148 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3149 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003150 // only one sink supported when connecting an input device to a mix
3151 if (patch->num_sinks > 1) {
3152 return INVALID_OPERATION;
3153 }
François Gaffie53615e22015-03-19 09:24:12 +01003154 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003155 if (inputDesc == NULL) {
3156 return BAD_VALUE;
3157 }
3158 if (patchDesc != 0) {
3159 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3160 return BAD_VALUE;
3161 }
3162 }
François Gaffie11d30102018-11-02 16:09:09 +01003163 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003165 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003166 return BAD_VALUE;
3167 }
3168
François Gaffie11d30102018-11-02 16:09:09 +01003169 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003170 patch->sinks[0].sample_rate,
3171 NULL, /*updatedSampleRate*/
3172 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003173 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003174 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003175 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003176 // FIXME for the parameter type,
3177 // and the NONE
3178 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003179 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003180 return INVALID_OPERATION;
3181 }
3182 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003183 ALOGV("%s() setting device %s on output %d", __func__,
3184 device->toString().c_str(), inputDesc->mIoHandle);
3185 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003186 index = mAudioPatches.indexOfKey(*handle);
3187 if (index >= 0) {
3188 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3189 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3190 }
3191 patchDesc = mAudioPatches.valueAt(index);
3192 patchDesc->mUid = uid;
3193 ALOGV("createAudioPatch() success");
3194 } else {
3195 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3196 return INVALID_OPERATION;
3197 }
3198 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3199 // device to device connection
3200 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003201 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003202 return BAD_VALUE;
3203 }
3204 }
François Gaffie11d30102018-11-02 16:09:09 +01003205 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003206 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003207 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003208 return BAD_VALUE;
3209 }
Eric Laurent874c42872014-08-08 15:13:39 -07003210
Eric Laurent6a94d692014-05-20 11:18:06 -07003211 //update source and sink with our own data as the data passed in the patch may
3212 // be incomplete.
3213 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003214 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003215
Eric Laurent874c42872014-08-08 15:13:39 -07003216 for (size_t i = 0; i < patch->num_sinks; i++) {
3217 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3218 ALOGV("createAudioPatch() source device but one sink is not a device");
3219 return INVALID_OPERATION;
3220 }
3221
François Gaffie11d30102018-11-02 16:09:09 +01003222 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003223 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003224 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003225 return BAD_VALUE;
3226 }
François Gaffie11d30102018-11-02 16:09:09 +01003227 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003228
Eric Laurent3bcf8592015-04-03 12:13:24 -07003229 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003230 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003231 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003232 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003233 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3234 (srcDevice->getModuleVersionMajor() < 3) ||
3235 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003236 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003237 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003238 return INVALID_OPERATION;
3239 }
Eric Laurent874c42872014-08-08 15:13:39 -07003240 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003241 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003242 // if the sink device is reachable via an opened output stream, request to go via
3243 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003244 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003245 if (output != AUDIO_IO_HANDLE_NONE) {
3246 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3247 if (outputDesc->isDuplicated()) {
3248 return INVALID_OPERATION;
3249 }
3250 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003251 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003252 newPatch.num_sources = 2;
3253 }
Eric Laurent83b88082014-06-20 18:31:16 -07003254 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003255 }
3256 // TODO: check from routing capabilities in config file and other conflicting patches
3257
Mikhail Naganovdc769682018-05-04 15:34:08 -07003258 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3259 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003260 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3261 status);
3262 return INVALID_OPERATION;
3263 }
3264 } else {
3265 return BAD_VALUE;
3266 }
3267 } else {
3268 return BAD_VALUE;
3269 }
3270 return NO_ERROR;
3271}
3272
3273status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3274 uid_t uid)
3275{
3276 ALOGV("releaseAudioPatch() patch %d", handle);
3277
3278 ssize_t index = mAudioPatches.indexOfKey(handle);
3279
3280 if (index < 0) {
3281 return BAD_VALUE;
3282 }
3283 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3284 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3285 mUidCached, patchDesc->mUid, uid);
3286 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3287 return INVALID_OPERATION;
3288 }
3289
3290 struct audio_patch *patch = &patchDesc->mPatch;
3291 patchDesc->mUid = mUidCached;
3292 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003293 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003294 if (outputDesc == NULL) {
3295 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3296 return BAD_VALUE;
3297 }
3298
François Gaffie11d30102018-11-02 16:09:09 +01003299 setOutputDevices(outputDesc,
3300 getNewOutputDevices(outputDesc, true /*fromCache*/),
3301 true,
3302 0,
3303 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003304 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3305 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003306 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003307 if (inputDesc == NULL) {
3308 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3309 return BAD_VALUE;
3310 }
3311 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003312 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003313 true,
3314 NULL);
3315 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003316 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3317 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3318 status, patchDesc->mAfPatchHandle);
3319 removeAudioPatch(patchDesc->mHandle);
3320 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003321 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003322 } else {
3323 return BAD_VALUE;
3324 }
3325 } else {
3326 return BAD_VALUE;
3327 }
3328 return NO_ERROR;
3329}
3330
3331status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3332 struct audio_patch *patches,
3333 unsigned int *generation)
3334{
François Gaffie53615e22015-03-19 09:24:12 +01003335 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003336 return BAD_VALUE;
3337 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003338 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003339 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003340}
3341
Eric Laurente1715a42014-05-20 11:30:42 -07003342status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003343{
Eric Laurente1715a42014-05-20 11:30:42 -07003344 ALOGV("setAudioPortConfig()");
3345
3346 if (config == NULL) {
3347 return BAD_VALUE;
3348 }
3349 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3350 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003351 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3352 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003353 }
3354
Eric Laurenta121f902014-06-03 13:32:54 -07003355 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003356 if (config->type == AUDIO_PORT_TYPE_MIX) {
3357 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003358 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003359 if (outputDesc == NULL) {
3360 return BAD_VALUE;
3361 }
Eric Laurent84c70242014-06-23 08:46:27 -07003362 ALOG_ASSERT(!outputDesc->isDuplicated(),
3363 "setAudioPortConfig() called on duplicated output %d",
3364 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003365 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003366 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003367 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003368 if (inputDesc == NULL) {
3369 return BAD_VALUE;
3370 }
Eric Laurenta121f902014-06-03 13:32:54 -07003371 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003372 } else {
3373 return BAD_VALUE;
3374 }
3375 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3376 sp<DeviceDescriptor> deviceDesc;
3377 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3378 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3379 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3380 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3381 } else {
3382 return BAD_VALUE;
3383 }
3384 if (deviceDesc == NULL) {
3385 return BAD_VALUE;
3386 }
Eric Laurenta121f902014-06-03 13:32:54 -07003387 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003388 } else {
3389 return BAD_VALUE;
3390 }
3391
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003392 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003393 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3394 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003395 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003396 audioPortConfig->toAudioPortConfig(&newConfig, config);
3397 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003398 }
Eric Laurenta121f902014-06-03 13:32:54 -07003399 if (status != NO_ERROR) {
3400 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003401 }
Eric Laurente1715a42014-05-20 11:30:42 -07003402
3403 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003404}
3405
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003406void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3407{
Eric Laurentd60560a2015-04-10 11:31:20 -07003408 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003409 clearAudioPatches(uid);
3410 clearSessionRoutes(uid);
3411}
3412
Eric Laurent6a94d692014-05-20 11:18:06 -07003413void AudioPolicyManager::clearAudioPatches(uid_t uid)
3414{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003415 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003416 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3417 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003418 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003419 }
3420 }
3421}
3422
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003423void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3424 audio_io_handle_t ouptutToSkip)
3425{
François Gaffie11d30102018-11-02 16:09:09 +01003426 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3427 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003428 for (size_t j = 0; j < mOutputs.size(); j++) {
3429 if (mOutputs.keyAt(j) == ouptutToSkip) {
3430 continue;
3431 }
3432 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3433 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3434 continue;
3435 }
3436 // If the default device for this strategy is on another output mix,
3437 // invalidate all tracks in this strategy to force re connection.
3438 // Otherwise select new device on the output mix.
3439 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003440 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003441 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3442 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3443 }
3444 }
3445 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003446 setOutputDevices(
3447 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003448 }
3449 }
3450}
3451
3452void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3453{
3454 // remove output routes associated with this uid
3455 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003456 for (size_t i = 0; i < mOutputs.size(); i++) {
3457 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003458 for (const auto& client : outputDesc->getClientIterable()) {
3459 if (client->hasPreferredDevice() && client->uid() == uid) {
3460 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3461 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003462 }
3463 }
3464 }
3465 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003466 for (const auto& strategy : affectedStrategies) {
3467 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003468 }
3469
3470 // remove input routes associated with this uid
3471 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003472 for (size_t i = 0; i < mInputs.size(); i++) {
3473 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003474 for (const auto& client : inputDesc->getClientIterable()) {
3475 if (client->hasPreferredDevice() && client->uid() == uid) {
3476 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3477 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003478 }
3479 }
3480 }
3481 // reroute inputs if necessary
3482 SortedVector<audio_io_handle_t> inputsToClose;
3483 for (size_t i = 0; i < mInputs.size(); i++) {
3484 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003485 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003486 inputsToClose.add(inputDesc->mIoHandle);
3487 }
3488 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003489 for (const auto& input : inputsToClose) {
3490 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003491 }
3492}
3493
Eric Laurentd60560a2015-04-10 11:31:20 -07003494void AudioPolicyManager::clearAudioSources(uid_t uid)
3495{
3496 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003497 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3498 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003499 stopAudioSource(mAudioSources.keyAt(i));
3500 }
3501 }
3502}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003503
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003504status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3505 audio_io_handle_t *ioHandle,
3506 audio_devices_t *device)
3507{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003508 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3509 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003510 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3511 *device = getDeviceAndMixForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003512
François Gaffiedf372692015-03-19 10:43:27 +01003513 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003514}
3515
Eric Laurentd60560a2015-04-10 11:31:20 -07003516status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003517 const audio_attributes_t *attributes,
3518 audio_port_handle_t *portId,
3519 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003520{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003521 ALOGV("%s", __FUNCTION__);
3522 *portId = AUDIO_PORT_HANDLE_NONE;
3523
3524 if (source == NULL || attributes == NULL || portId == NULL) {
3525 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3526 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003527 return BAD_VALUE;
3528 }
3529
Eric Laurentd60560a2015-04-10 11:31:20 -07003530 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3531 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003532 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3533 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003534 return INVALID_OPERATION;
3535 }
3536
François Gaffie11d30102018-11-02 16:09:09 +01003537 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003538 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003539 String8(source->ext.device.address),
3540 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003541 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003542 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003543 return BAD_VALUE;
3544 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003545
3546 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003547
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003548 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003549 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003550
3551 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003552 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003553 streamTypefromAttributesInt(attributes),
3554 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003555
3556 status_t status = connectAudioSource(sourceDesc);
3557 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003558 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003559 }
3560 return status;
3561}
3562
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003563status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003564{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003565 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003566
3567 // make sure we only have one patch per source.
3568 disconnectAudioSource(sourceDesc);
3569
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003570 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003571 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003572 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003573 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003574
François Gaffie11d30102018-11-02 16:09:09 +01003575 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3576 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3577 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3578 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3579 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003580
3581 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003582
François Gaffie11d30102018-11-02 16:09:09 +01003583 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3584 srcDevice->getModuleVersionMajor() >= 3 &&
3585 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3586 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003587 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003588 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003589 // create patch between src device and output device
3590 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003591 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003592 audio_attributes_t resultAttr;
3593 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3594 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3595 config.sample_rate = sourceDesc->config().sample_rate;
3596 config.channel_mask = sourceDesc->config().channel_mask;
3597 config.format = sourceDesc->config().format;
3598 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3599 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3600 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3601 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003602 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003603 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003604 return INVALID_OPERATION;
3605 }
3606 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3607 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003608 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003609 return INVALID_OPERATION;
3610 }
Eric Laurent733ce942017-12-07 12:18:25 -08003611 status_t status = outputDesc->start();
3612 if (status != NO_ERROR) {
3613 return status;
3614 }
3615
Eric Laurentd60560a2015-04-10 11:31:20 -07003616 // create a special patch with no sink and two sources:
3617 // - the second source indicates to PatchPanel through which output mix this patch should
3618 // be connected as well as the stream type for volume control
3619 // - the sink is defined by whatever output device is currently selected for the output
3620 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003621 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003622 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003623 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003624 &afPatchHandle,
3625 0);
3626 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3627 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003628 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003629 if (status != NO_ERROR) {
3630 ALOGW("%s patch panel could not connect device patch, error %d",
3631 __FUNCTION__, status);
3632 return INVALID_OPERATION;
3633 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003634
3635 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3636 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3637 return INVALID_OPERATION;
3638 }
3639 outputDesc->addClient(sourceDesc);
3640
Eric Laurentd60560a2015-04-10 11:31:20 -07003641 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003642 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003643
3644 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003645 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003646 return status;
3647 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003648 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003649 if (delayMs != 0) {
3650 usleep(delayMs * 1000);
3651 }
3652 }
3653
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003654 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3655 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003656
3657 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003658}
3659
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003660status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003661{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003662 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3663 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003664 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003665 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003666 return BAD_VALUE;
3667 }
3668 status_t status = disconnectAudioSource(sourceDesc);
3669
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003670 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003671 return status;
3672}
3673
Andy Hung2ddee192015-12-18 17:34:44 -08003674status_t AudioPolicyManager::setMasterMono(bool mono)
3675{
3676 if (mMasterMono == mono) {
3677 return NO_ERROR;
3678 }
3679 mMasterMono = mono;
3680 // if enabling mono we close all offloaded devices, which will invalidate the
3681 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3682 // for recreating the new AudioTrack as non-offloaded PCM.
3683 //
3684 // If disabling mono, we leave all tracks as is: we don't know which clients
3685 // and tracks are able to be recreated as offloaded. The next "song" should
3686 // play back offloaded.
3687 if (mMasterMono) {
3688 Vector<audio_io_handle_t> offloaded;
3689 for (size_t i = 0; i < mOutputs.size(); ++i) {
3690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3691 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3692 offloaded.push(desc->mIoHandle);
3693 }
3694 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003695 for (const auto& handle : offloaded) {
3696 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003697 }
3698 }
3699 // update master mono for all remaining outputs
3700 for (size_t i = 0; i < mOutputs.size(); ++i) {
3701 updateMono(mOutputs.keyAt(i));
3702 }
3703 return NO_ERROR;
3704}
3705
3706status_t AudioPolicyManager::getMasterMono(bool *mono)
3707{
3708 *mono = mMasterMono;
3709 return NO_ERROR;
3710}
3711
Eric Laurentac9cef52017-06-09 15:46:26 -07003712float AudioPolicyManager::getStreamVolumeDB(
3713 audio_stream_type_t stream, int index, audio_devices_t device)
3714{
3715 return computeVolume(stream, index, device);
3716}
3717
jiabin81772902018-04-02 17:52:27 -07003718status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3719 audio_format_t *surroundFormats,
3720 bool *surroundFormatsEnabled,
3721 bool reported)
3722{
3723 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3724 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3725 return BAD_VALUE;
3726 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003727 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3728 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003729
3730 size_t formatsWritten = 0;
3731 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003732 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003733 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003734 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003735 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003736 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3737 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3738 FormatVector supportedFormats =
3739 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3740 for (size_t j = 0; j < supportedFormats.size(); j++) {
3741 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3742 formats.insert(supportedFormats[j]);
3743 } else {
3744 for (const auto& pair : mConfig.getSurroundFormats()) {
3745 if (pair.second.count(supportedFormats[j]) != 0) {
3746 formats.insert(pair.first);
3747 break;
3748 }
3749 }
3750 }
3751 }
jiabin81772902018-04-02 17:52:27 -07003752 }
3753 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003754 for (const auto& pair : mConfig.getSurroundFormats()) {
3755 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003756 }
3757 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003758 *numSurroundFormats = formats.size();
3759 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3760 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003761 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003762 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003763 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003764 bool formatEnabled = true;
3765 switch (forceUse) {
3766 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3767 formatEnabled = mManualSurroundFormats.count(format) != 0;
3768 break;
3769 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3770 formatEnabled = false;
3771 break;
3772 default: // AUTO or ALWAYS => true
3773 break;
jiabin81772902018-04-02 17:52:27 -07003774 }
3775 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3776 }
jiabin81772902018-04-02 17:52:27 -07003777 }
3778 return NO_ERROR;
3779}
3780
3781status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3782{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003783 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003784 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3785 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003786 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003787 return BAD_VALUE;
3788 }
3789
Mikhail Naganov100f0122018-11-29 11:22:16 -08003790 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3791 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003792 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003793 return INVALID_OPERATION;
3794 }
3795
Mikhail Naganov100f0122018-11-29 11:22:16 -08003796 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003797 return NO_ERROR;
3798 }
3799
Mikhail Naganov100f0122018-11-29 11:22:16 -08003800 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003801 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003802 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003803 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003804 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003805 }
3806 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003807 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003808 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003809 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003810 }
3811 }
3812
3813 sp<SwAudioOutputDescriptor> outputDesc;
3814 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003815 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003816 AUDIO_DEVICE_OUT_HDMI);
3817 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3818 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003819 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003820 String8 name = hdmiOutputDevices[i]->getName();
3821 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3822 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3823 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003824 name.c_str(),
3825 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003826 if (status != NO_ERROR) {
3827 continue;
3828 }
3829 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3830 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3831 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003832 name.c_str(),
3833 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003834 profileUpdated |= (status == NO_ERROR);
3835 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003836 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003837 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003838 AUDIO_DEVICE_IN_HDMI);
3839 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3840 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003841 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003842 String8 name = hdmiInputDevices[i]->getName();
3843 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3844 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3845 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003846 name.c_str(),
3847 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003848 if (status != NO_ERROR) {
3849 continue;
3850 }
3851 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3852 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3853 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003854 name.c_str(),
3855 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07003856 profileUpdated |= (status == NO_ERROR);
3857 }
3858
jiabin81772902018-04-02 17:52:27 -07003859 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003860 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003861 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003862 }
3863
3864 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3865}
3866
Eric Laurentf32108e2018-10-04 17:22:04 -07003867void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003868{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003869 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003870
Eric Laurenta9f86652018-11-28 17:23:11 -08003871 for (size_t i = 0; i < mInputs.size(); i++) {
3872 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3873 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003874 for (const auto& client : clients) {
3875 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003876 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003877 }
3878 }
3879 }
3880}
3881
jiabin6012f912018-11-02 17:06:30 -07003882bool AudioPolicyManager::isHapticPlaybackSupported()
3883{
3884 for (const auto& hwModule : mHwModules) {
3885 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3886 for (const auto &outProfile : outputProfiles) {
3887 struct audio_port audioPort;
3888 outProfile->toAudioPort(&audioPort);
3889 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3890 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3891 return true;
3892 }
3893 }
3894 }
3895 }
3896 return false;
3897}
3898
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003899status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003900{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003901 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003902
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003903 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003904 if (patchDesc == 0) {
3905 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003906 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003907 return BAD_VALUE;
3908 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003909 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003910
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003911 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003912 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003913 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003914 if (status == NO_ERROR) {
3915 swOutputDesc->stop();
3916 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003917 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3918 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003919 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003920 if (hwOutputDesc != 0) {
3921 // release patch between src device and output device
3922 // close Hwoutput and remove from mHwOutputs
3923 } else {
3924 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3925 }
3926 }
3927 return NO_ERROR;
3928}
3929
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003930sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003931 audio_io_handle_t output, routing_strategy strategy)
3932{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003933 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003934 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003935 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3936 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003937 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003938 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003939 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3940 source = sourceDesc;
3941 break;
3942 }
3943 }
3944 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003945}
3946
Eric Laurente552edb2014-03-10 17:42:56 -07003947// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003948// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003949// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003950uint32_t AudioPolicyManager::nextAudioPortGeneration()
3951{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003952 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003953}
3954
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003955// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3956static const char *kConfigLocationList[] =
3957 {"/odm/etc", "/vendor/etc", "/system/etc"};
3958static const int kConfigLocationListSize =
3959 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3960
3961static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3962 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003963 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003964 status_t ret;
3965
Petri Gyntherf497f292018-04-17 18:46:10 -07003966 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3967 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3968 // A2DP offload supported but disabled: try to use special XML file
3969 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3970 }
3971 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3972
3973 for (const char* fileName : fileNames) {
3974 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003975 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3976 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003977 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003978 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003979 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003980 return ret;
3981 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003982 }
3983 }
3984 return ret;
3985}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003986
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003987AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3988 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003989 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003990 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003991 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003992 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003993 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003994 mVolumeCurves(new VolumeCurvesCollection()),
3995 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003996 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003997 mAudioPortGeneration(1),
3998 mBeaconMuteRefCount(0),
3999 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004000 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004001 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004002 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004003 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004004{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004005}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004006
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004007AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4008 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4009{
4010 loadConfig();
4011 initialize();
4012}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004013
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004014// This check is to catch any legacy platform updating to Q without having
4015// switched to XML since its deprecation on O.
4016// TODO: after Q release, remove this check and flag as XML is now the only
4017// option and all legacy platform should have transitioned to XML.
4018#ifndef USE_XML_AUDIO_POLICY_CONF
4019#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01004020#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004021
4022void AudioPolicyManager::loadConfig() {
4023 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004024 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004025 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004026 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004027}
4028
4029status_t AudioPolicyManager::initialize() {
4030 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01004031
4032 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01004033 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4034 if (!engineInstance) {
4035 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004036 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004037 }
4038 // Retrieve the Policy Manager Interface
4039 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4040 if (mEngine == NULL) {
4041 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004042 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004043 }
4044 mEngine->setObserver(this);
4045 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004046 if (status != NO_ERROR) {
4047 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4048 return status;
4049 }
François Gaffie2110e042015-03-24 08:41:51 +01004050
Eric Laurent3a4311c2014-03-17 12:00:47 -07004051 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004052 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08004053 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004054 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004055 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4056 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004057 continue;
4058 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004059 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004060 // open all output streams needed to access attached devices
4061 // except for direct output streams that are only opened when they are actually
4062 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004064 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004065 if (!outProfile->canOpenNewIo()) {
4066 ALOGE("Invalid Output profile max open count %u for profile %s",
4067 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4068 continue;
4069 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004070 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004071 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 continue;
4073 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004074 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004075 mTtsOutputAvailable = true;
4076 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004077
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004078 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004079 continue;
4080 }
François Gaffie11d30102018-11-02 16:09:09 +01004081 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4082 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4083 sp<DeviceDescriptor> supportedDevice = 0;
4084 if (supportedDevices.contains(mDefaultOutputDevice)) {
4085 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07004086 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004087 // choose first device present in profile's SupportedDevices also part of
4088 // mAvailableOutputDevices.
4089 if (availProfileDevices.isEmpty()) {
4090 continue;
4091 }
4092 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004093 }
François Gaffie11d30102018-11-02 16:09:09 +01004094 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004095 continue;
4096 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004097 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4098 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004099 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004100 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4101 AUDIO_STREAM_DEFAULT,
4102 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004103 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004104 ALOGW("Cannot open output stream for devices %s on hw module %s",
4105 supportedDevice->toString().c_str(), hwModule->getName());
4106 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004107 }
François Gaffie11d30102018-11-02 16:09:09 +01004108 for (const auto &device : availProfileDevices) {
4109 // give a valid ID to an attached device once confirmed it is reachable
4110 if (!device->isAttached()) {
4111 device->attach(hwModule);
4112 }
4113 }
4114 if (mPrimaryOutput == 0 &&
4115 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4116 mPrimaryOutput = outputDesc;
4117 }
4118 addOutput(output, outputDesc);
4119 setOutputDevices(outputDesc,
4120 DeviceVector(supportedDevice),
4121 true,
4122 0,
4123 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004124 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004125 // open input streams needed to access attached devices to validate
4126 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004127 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004128 if (!inProfile->canOpenNewIo()) {
4129 ALOGE("Invalid Input profile max open count %u for profile %s",
4130 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4131 continue;
4132 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004133 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004134 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004135 continue;
4136 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004137 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004138 // available input devices
4139 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4140 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4141 if (availProfileDevices.isEmpty()) {
4142 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004143 continue;
4144 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004145 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004146 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004147
Eric Laurentd78f1532014-09-16 16:38:20 -07004148 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004149 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004150 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004151 AUDIO_SOURCE_MIC,
4152 AUDIO_INPUT_FLAG_NONE,
4153 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004154 if (status != NO_ERROR) {
4155 ALOGW("Cannot open input stream for device %s on hw module %s",
4156 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004157 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004158 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004159 }
François Gaffie11d30102018-11-02 16:09:09 +01004160 for (const auto &device : availProfileDevices) {
4161 // give a valid ID to an attached device once confirmed it is reachable
4162 if (!device->isAttached()) {
4163 device->attach(hwModule);
4164 device->importAudioPort(inProfile, true);
4165 }
4166 }
4167 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004168 }
4169 }
4170 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004171 auto checkAndSetAvailable = [this](auto& devices) {
Eric Laurent7f0f4312019-01-18 10:47:14 -08004172 for (size_t i = 0; i < devices.size();) {
4173 const auto &device = devices[i];
François Gaffie11d30102018-11-02 16:09:09 +01004174 if (!device->isAttached()) {
4175 ALOGW("device %s is unreachable", device->toString().c_str());
4176 devices.remove(device);
4177 continue;
4178 }
4179 // Device is now validated and can be appended to the available devices of the engine
4180 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent7f0f4312019-01-18 10:47:14 -08004181 i++;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 }
François Gaffie11d30102018-11-02 16:09:09 +01004183 };
4184 checkAndSetAvailable(mAvailableOutputDevices);
4185 checkAndSetAvailable(mAvailableInputDevices);
4186
Eric Laurent3a4311c2014-03-17 12:00:47 -07004187 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004188 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4189 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4190 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004191 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004192 }
jiabin9ff780e2018-03-19 18:19:52 -07004193 // If microphones address is empty, set it according to device type
4194 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004195 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004196 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004197 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004198 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004199 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004200 }
4201 }
4202 }
Eric Laurente552edb2014-03-10 17:42:56 -07004203
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004204 if (mPrimaryOutput == 0) {
4205 ALOGE("Failed to open primary output");
4206 status = NO_INIT;
4207 }
Eric Laurente552edb2014-03-10 17:42:56 -07004208
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004209 // Silence ALOGV statements
4210 property_set("log.tag." LOG_TAG, "D");
4211
Eric Laurente552edb2014-03-10 17:42:56 -07004212 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004213 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004214}
4215
Eric Laurente0720872014-03-11 09:30:41 -07004216AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004217{
Eric Laurente552edb2014-03-10 17:42:56 -07004218 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004219 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004220 }
4221 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004222 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004223 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004224 mAvailableOutputDevices.clear();
4225 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004226 mOutputs.clear();
4227 mInputs.clear();
4228 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004229 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004230 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004231}
4232
Eric Laurente0720872014-03-11 09:30:41 -07004233status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004234{
Eric Laurent87ffa392015-05-22 10:32:38 -07004235 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004236}
4237
Eric Laurente552edb2014-03-10 17:42:56 -07004238// ---
4239
Eric Laurent98e38192018-02-15 18:31:53 -08004240void AudioPolicyManager::addOutput(audio_io_handle_t output,
4241 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004242{
Eric Laurent1c333e22014-05-20 10:48:17 -07004243 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004244 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004245 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004246 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004247 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004248}
4249
François Gaffie53615e22015-03-19 09:24:12 +01004250void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4251{
4252 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004253 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004254}
4255
Eric Laurent98e38192018-02-15 18:31:53 -08004256void AudioPolicyManager::addInput(audio_io_handle_t input,
4257 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004258{
Eric Laurent1c333e22014-05-20 10:48:17 -07004259 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004261}
Eric Laurente552edb2014-03-10 17:42:56 -07004262
François Gaffie11d30102018-11-02 16:09:09 +01004263status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004264 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004265 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004266{
François Gaffie11d30102018-11-02 16:09:09 +01004267 audio_devices_t deviceType = device->type();
4268 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004269 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004270
François Gaffie11d30102018-11-02 16:09:09 +01004271 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004272 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004273 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004274 }
Eric Laurente552edb2014-03-10 17:42:56 -07004275
Eric Laurent3b73df72014-03-11 09:06:29 -07004276 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 // first list already open outputs that can be routed to this device
4278 for (size_t i = 0; i < mOutputs.size(); i++) {
4279 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004280 if (!desc->isDuplicated() && desc->supportsDevice(device)
4281 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004282 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4283 mOutputs.keyAt(i), device->toString().c_str());
4284 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004285 }
4286 }
4287 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004288 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004289 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004290 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4291 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004292 if (profile->supportsDevice(device)) {
4293 profiles.add(profile);
4294 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4295 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004296 }
4297 }
4298 }
4299
Eric Laurent7b279bb2015-12-14 10:18:23 -08004300 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004301
Eric Laurente552edb2014-03-10 17:42:56 -07004302 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004303 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004304 return BAD_VALUE;
4305 }
4306
4307 // open outputs for matching profiles if needed. Direct outputs are also opened to
4308 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4309 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004310 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004311
4312 // nothing to do if one output is already opened for this profile
4313 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004314 for (j = 0; j < outputs.size(); j++) {
4315 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004316 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004317 // matching profile: save the sample rates, format and channel masks supported
4318 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004319 if (audio_device_is_digital(deviceType)) {
4320 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004321 }
Eric Laurente552edb2014-03-10 17:42:56 -07004322 break;
4323 }
4324 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004325 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004326 continue;
4327 }
4328
Eric Laurent3974e3b2017-12-07 17:58:43 -08004329 if (!profile->canOpenNewIo()) {
4330 ALOGW("Max Output number %u already opened for this profile %s",
4331 profile->maxOpenCount, profile->getTagName().c_str());
4332 continue;
4333 }
4334
Eric Laurent83efe1c2017-07-09 16:51:08 -07004335 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004336 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004337 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004338 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004339 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004340 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004341
Eric Laurentfe231122017-11-17 17:48:06 -08004342 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004343 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004344 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004345 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004346 mpClientInterface->setParameters(output, String8(param));
4347 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004348 }
François Gaffie11d30102018-11-02 16:09:09 +01004349 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004350 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004351 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004352 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004353 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004354 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004355 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004356 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004357 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4358 profile->pickAudioProfile(
4359 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004360 config.offload_info.sample_rate = config.sample_rate;
4361 config.offload_info.channel_mask = config.channel_mask;
4362 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004363
François Gaffie11d30102018-11-02 16:09:09 +01004364 status_t status = desc->open(&config, DeviceVector(device),
4365 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004366 AUDIO_OUTPUT_FLAG_NONE, &output);
4367 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004368 output = AUDIO_IO_HANDLE_NONE;
4369 }
Eric Laurentd4692962014-05-05 18:13:44 -07004370 }
4371
Eric Laurentcf2c0212014-07-25 16:20:43 -07004372 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004373 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004374 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004375 sp<AudioPolicyMix> policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004376 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) == NO_ERROR) {
4377 policyMix->setOutput(desc);
4378 desc->mPolicyMix = policyMix->getMix();
4379 } else {
4380 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004381 address.string());
4382 }
François Gaffie036e1e92015-03-19 10:16:24 +01004383
Eric Laurent87ffa392015-05-22 10:32:38 -07004384 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4385 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004386 // no duplicated output for direct outputs and
4387 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004388 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004389
Eric Laurentd4692962014-05-05 18:13:44 -07004390 //TODO: configure audio effect output stage here
4391
4392 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004393 sp<SwAudioOutputDescriptor> dupOutputDesc =
4394 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4395 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4396 &duplicatedOutput);
4397 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004398 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004399 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004400 } else {
4401 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004402 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004403 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004404 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004406 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004407 }
Eric Laurente552edb2014-03-10 17:42:56 -07004408 }
4409 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004410 } else {
4411 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004412 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004413 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004414 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004415 profiles.removeAt(profile_index);
4416 profile_index--;
4417 } else {
4418 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004419 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004420 if (audio_device_is_digital(deviceType)) {
4421 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004422 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004423
François Gaffie11d30102018-11-02 16:09:09 +01004424 if (device_distinguishes_on_address(deviceType)) {
4425 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4426 device->toString().c_str());
4427 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4428 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004429 }
Eric Laurente552edb2014-03-10 17:42:56 -07004430 ALOGV("checkOutputsForDevice(): adding output %d", output);
4431 }
4432 }
4433
4434 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004435 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004436 return BAD_VALUE;
4437 }
Eric Laurentd4692962014-05-05 18:13:44 -07004438 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004439 // check if one opened output is not needed any more after disconnecting one device
4440 for (size_t i = 0; i < mOutputs.size(); i++) {
4441 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004442 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004443 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004444 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4445 && desc->deviceSupportsEncodedFormats(deviceType)) {
François Gaffie11d30102018-11-02 16:09:09 +01004446 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004447 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004448 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4449 mOutputs.keyAt(i));
4450 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004451 }
Eric Laurente552edb2014-03-10 17:42:56 -07004452 }
4453 }
Eric Laurentd4692962014-05-05 18:13:44 -07004454 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004455 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004456 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4457 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004458 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004459 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004460 "clearing direct output profile %zu on module %s",
4461 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004462 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004463 }
4464 }
4465 }
4466 }
4467 return NO_ERROR;
4468}
4469
François Gaffie11d30102018-11-02 16:09:09 +01004470status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004471 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004472 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004473{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004474 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004475
François Gaffie11d30102018-11-02 16:09:09 +01004476 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004477 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004478 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004479 }
4480
Eric Laurentd4692962014-05-05 18:13:44 -07004481 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4482 // first list already open inputs that can be routed to this device
4483 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4484 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004485 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4487 inputs.add(mInputs.keyAt(input_index));
4488 }
4489 }
4490
4491 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004492 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004493 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004494 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004495 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004496 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004497 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004498
François Gaffie11d30102018-11-02 16:09:09 +01004499 if (profile->supportsDevice(device)) {
4500 profiles.add(profile);
4501 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4502 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004503 }
4504 }
4505 }
4506
4507 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004508 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004509 return BAD_VALUE;
4510 }
4511
4512 // open inputs for matching profiles if needed. Direct inputs are also opened to
4513 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4514 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4515
Eric Laurent1c333e22014-05-20 10:48:17 -07004516 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004517
Eric Laurentd4692962014-05-05 18:13:44 -07004518 // nothing to do if one input is already opened for this profile
4519 size_t input_index;
4520 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4521 desc = mInputs.valueAt(input_index);
4522 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004523 if (audio_device_is_digital(device->type())) {
4524 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004525 }
Eric Laurentd4692962014-05-05 18:13:44 -07004526 break;
4527 }
4528 }
4529 if (input_index != mInputs.size()) {
4530 continue;
4531 }
4532
Eric Laurent3974e3b2017-12-07 17:58:43 -08004533 if (!profile->canOpenNewIo()) {
4534 ALOGW("Max Input number %u already opened for this profile %s",
4535 profile->maxOpenCount, profile->getTagName().c_str());
4536 continue;
4537 }
4538
Eric Laurentfe231122017-11-17 17:48:06 -08004539 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004540 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004541 status_t status = desc->open(nullptr,
4542 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004543 AUDIO_SOURCE_MIC,
4544 AUDIO_INPUT_FLAG_NONE,
4545 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004546
Eric Laurentcf2c0212014-07-25 16:20:43 -07004547 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004548 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004549 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004550 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004551 mpClientInterface->setParameters(input, String8(param));
4552 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004553 }
François Gaffie11d30102018-11-02 16:09:09 +01004554 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004555 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004556 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004557 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004558 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004559 }
4560
4561 if (input != 0) {
4562 addInput(input, desc);
4563 }
4564 } // endif input != 0
4565
Eric Laurentcf2c0212014-07-25 16:20:43 -07004566 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004567 ALOGW("%s could not open input for device %s", __func__,
4568 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004569 profiles.removeAt(profile_index);
4570 profile_index--;
4571 } else {
4572 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004573 if (audio_device_is_digital(device->type())) {
4574 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004575 }
Eric Laurentd4692962014-05-05 18:13:44 -07004576 ALOGV("checkInputsForDevice(): adding input %d", input);
4577 }
4578 } // end scan profiles
4579
4580 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004581 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004582 return BAD_VALUE;
4583 }
4584 } else {
4585 // Disconnect
4586 // check if one opened input is not needed any more after disconnecting one device
4587 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4588 desc = mInputs.valueAt(input_index);
Francois Gaffie716e1432019-01-14 16:58:59 +01004589 if (!mAvailableInputDevices.containsAtLeastOne(desc->supportedDevices())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004590 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4591 mInputs.keyAt(input_index));
4592 inputs.add(mInputs.keyAt(input_index));
4593 }
4594 }
4595 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004596 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004597 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004598 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004599 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004600 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004601 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004602 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4603 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004604 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004605 }
4606 }
4607 }
4608 } // end disconnect
4609
4610 return NO_ERROR;
4611}
4612
4613
Eric Laurente0720872014-03-11 09:30:41 -07004614void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004615{
4616 ALOGV("closeOutput(%d)", output);
4617
Eric Laurentc75307b2015-03-17 15:29:32 -07004618 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004619 if (outputDesc == NULL) {
4620 ALOGW("closeOutput() unknown output %d", output);
4621 return;
4622 }
François Gaffie036e1e92015-03-19 10:16:24 +01004623 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004624
Eric Laurente552edb2014-03-10 17:42:56 -07004625 // look for duplicated outputs connected to the output being removed.
4626 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004627 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004628 if (dupOutputDesc->isDuplicated() &&
4629 (dupOutputDesc->mOutput1 == outputDesc ||
4630 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004631 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004632 if (dupOutputDesc->mOutput1 == outputDesc) {
4633 outputDesc2 = dupOutputDesc->mOutput2;
4634 } else {
4635 outputDesc2 = dupOutputDesc->mOutput1;
4636 }
4637 // As all active tracks on duplicated output will be deleted,
4638 // and as they were also referenced on the other output, the reference
4639 // count for their stream type must be adjusted accordingly on
4640 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004641 const bool wasActive = outputDesc2->isActive();
4642 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4643 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
Eric Laurent733ce942017-12-07 12:18:25 -08004645 // stop() will be a no op if the output is still active but is needed in case all
4646 // active streams refcounts where cleared above
4647 if (wasActive) {
4648 outputDesc2->stop();
4649 }
Eric Laurente552edb2014-03-10 17:42:56 -07004650 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4651 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4652
4653 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004654 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004655 }
4656 }
4657
Eric Laurent05b90f82014-08-27 15:32:29 -07004658 nextAudioPortGeneration();
4659
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004660 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004661 if (index >= 0) {
4662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004663 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004664 mAudioPatches.removeItemsAt(index);
4665 mpClientInterface->onAudioPatchListUpdate();
4666 }
4667
Eric Laurentfe231122017-11-17 17:48:06 -08004668 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004669
François Gaffie53615e22015-03-19 09:24:12 +01004670 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004671 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004672
4673 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4674 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004675 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004676 bool directOutputOpen = false;
4677 for (size_t i = 0; i < mOutputs.size(); i++) {
4678 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4679 directOutputOpen = true;
4680 break;
4681 }
4682 }
4683 if (!directOutputOpen) {
4684 ALOGV("no direct outputs open, reset MSD patch");
4685 setMsdPatch();
4686 }
4687 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004688}
4689
4690void AudioPolicyManager::closeInput(audio_io_handle_t input)
4691{
4692 ALOGV("closeInput(%d)", input);
4693
4694 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4695 if (inputDesc == NULL) {
4696 ALOGW("closeInput() unknown input %d", input);
4697 return;
4698 }
4699
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004701
François Gaffie11d30102018-11-02 16:09:09 +01004702 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004703 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004704 if (index >= 0) {
4705 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004706 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004707 mAudioPatches.removeItemsAt(index);
4708 mpClientInterface->onAudioPatchListUpdate();
4709 }
4710
Eric Laurentfe231122017-11-17 17:48:06 -08004711 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004712 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004713
François Gaffie11d30102018-11-02 16:09:09 +01004714 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4715 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004716 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4717 SoundTrigger::setCaptureState(false);
4718 }
Eric Laurente552edb2014-03-10 17:42:56 -07004719}
4720
François Gaffie11d30102018-11-02 16:09:09 +01004721SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4722 const DeviceVector &devices,
4723 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004724{
4725 SortedVector<audio_io_handle_t> outputs;
4726
François Gaffie11d30102018-11-02 16:09:09 +01004727 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004728 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004729 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004730 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004731 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004732 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
4733 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01004734 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004735 outputs.add(openOutputs.keyAt(i));
4736 }
4737 }
4738 return outputs;
4739}
4740
Mikhail Naganov37977152018-07-11 15:54:44 -07004741void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4742{
4743 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4744 // output is suspended before any tracks are moved to it
4745 checkA2dpSuspend();
4746 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004747 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004748 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004749 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004750 setMsdPatch();
4751 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004752}
4753
Eric Laurente0720872014-03-11 09:30:41 -07004754void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004755{
François Gaffie11d30102018-11-02 16:09:09 +01004756 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4757 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4758 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4759 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004760
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004761 // also take into account external policy-related changes: add all outputs which are
4762 // associated with policies in the "before" and "after" output vectors
4763 ALOGVV("checkOutputForStrategy(): policy related outputs");
4764 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004765 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004766 if (desc != 0 && desc->mPolicyMix != NULL) {
4767 srcOutputs.add(desc->mIoHandle);
4768 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4769 }
4770 }
4771 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004772 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004773 if (desc != 0 && desc->mPolicyMix != NULL) {
4774 dstOutputs.add(desc->mIoHandle);
4775 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4776 }
4777 }
4778
Francois Gaffie716e1432019-01-14 16:58:59 +01004779 if (!dstOutputs.isEmpty() && srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004780 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4781 // audio from invalidated tracks will be rendered when unmuting
4782 uint32_t maxLatency = 0;
4783 for (audio_io_handle_t srcOut : srcOutputs) {
4784 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4785 if (desc != 0 && maxLatency < desc->latency()) {
4786 maxLatency = desc->latency();
4787 }
4788 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004789 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
4790 "%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4791 std::to_string(srcOutputs[0]).c_str(),
4792 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004793 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004794 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004795 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4796 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004797 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004798 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4799 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004800 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004801 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004802 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004803 if (source != 0){
4804 connectAudioSource(source);
4805 }
Eric Laurente552edb2014-03-10 17:42:56 -07004806 }
4807
4808 // Move effects associated to this strategy from previous output to new output
4809 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004810 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004811 }
4812 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004813 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004814 if (getStrategy((audio_stream_type_t)i) == strategy) {
4815 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004816 }
4817 }
4818 }
4819}
4820
Eric Laurente0720872014-03-11 09:30:41 -07004821void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004822{
François Gaffie2110e042015-03-24 08:41:51 +01004823 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004824 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004825 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004826 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004827 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004828 checkOutputForStrategy(STRATEGY_SONIFICATION);
4829 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004830 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004831 checkOutputForStrategy(STRATEGY_MEDIA);
4832 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004833 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004834}
4835
Eric Laurente0720872014-03-11 09:30:41 -07004836void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004837{
François Gaffie53615e22015-03-19 09:24:12 +01004838 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004839 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004840 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004841 return;
4842 }
4843
Eric Laurent3a4311c2014-03-17 12:00:47 -07004844 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004845 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4846 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4847 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004848
4849 // if suspended, restore A2DP output if:
4850 // ((SCO device is NOT connected) ||
4851 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4852 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004853 //
Eric Laurentf732e072016-08-03 19:30:28 -07004854 // if not suspended, suspend A2DP output if:
4855 // (SCO device is connected) &&
4856 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4857 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004858 //
4859 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004860 if (!isScoConnected ||
4861 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4862 AUDIO_POLICY_FORCE_BT_SCO) &&
4863 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4864 AUDIO_POLICY_FORCE_BT_SCO) &&
4865 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004866 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004867
4868 mpClientInterface->restoreOutput(a2dpOutput);
4869 mA2dpSuspended = false;
4870 }
4871 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004872 if (isScoConnected &&
4873 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4874 AUDIO_POLICY_FORCE_BT_SCO) ||
4875 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4876 AUDIO_POLICY_FORCE_BT_SCO) ||
4877 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004878 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004879
4880 mpClientInterface->suspendOutput(a2dpOutput);
4881 mA2dpSuspended = true;
4882 }
4883 }
4884}
4885
Eric Laurent97ac8712018-07-27 18:59:02 -07004886template <class IoDescriptor, class Filter>
4887sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4888 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4889{
4890 auto activeClients = desc->clientsList(true /*activeOnly*/);
4891 auto activeClientsWithRoute =
4892 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4893 active = activeClients.size() > 0;
4894 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4895 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4896 }
4897 return nullptr;
4898}
4899
4900template <class IoCollection, class Filter>
4901sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4902 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4903{
4904 sp<DeviceDescriptor> device;
4905 for (size_t i = 0; i < ioCollection.size(); i++) {
4906 auto desc = ioCollection.valueAt(i);
4907 bool active;
4908 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4909 if (active && curDevice == nullptr) {
4910 return nullptr;
4911 } else if (curDevice != nullptr) {
4912 device = curDevice;
4913 }
4914 }
4915 return device;
4916}
4917
François Gaffie11d30102018-11-02 16:09:09 +01004918DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4919 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004920{
François Gaffie11d30102018-11-02 16:09:09 +01004921 DeviceVector devices;
4922
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004923 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 if (index >= 0) {
4925 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4926 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004927 ALOGV("%s device %s forced by patch %d", __func__,
4928 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4929 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 }
4931 }
4932
Eric Laurent97ac8712018-07-27 18:59:02 -07004933 // Honor explicit routing requests only if no client using default routing is active on this
4934 // input: a specific app can not force routing for other apps by setting a preferred device.
4935 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004936 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004937 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004938 if (device != nullptr) {
4939 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004940 }
4941
Eric Laurente552edb2014-03-10 17:42:56 -07004942 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004943 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004944 // use device for strategy enforced audible
4945 // 2: we are in call or the strategy phone is active on the output:
4946 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004947 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004948 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004949 // 4: the strategy for enforced audible is active but not enforced on the output:
4950 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004951 // 5: the strategy accessibility is active on the output:
4952 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004953 // 6: the strategy "respectful" sonification is active on the output:
4954 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004955 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004956 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004957 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004958 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004959 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004960 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004961
4962 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4963 // with a refined rule considering mutually exclusive devices (using same backend)
4964 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004965 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004966 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004967 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004968 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004969 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004970 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004971 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01004972 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004973 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004974 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004975 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01004976 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004977 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01004978 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004979 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01004980 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004981 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01004982 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004983 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01004984 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004985 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01004986 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004987 }
4988
François Gaffie11d30102018-11-02 16:09:09 +01004989 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
4990 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004991}
4992
François Gaffie11d30102018-11-02 16:09:09 +01004993sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4994 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004995{
François Gaffie11d30102018-11-02 16:09:09 +01004996 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004997
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004998 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 if (index >= 0) {
5000 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5001 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005002 ALOGV("getNewInputDevice() device %s forced by patch %d",
5003 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5004 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 }
5006 }
5007
Eric Laurent97ac8712018-07-27 18:59:02 -07005008 // Honor explicit routing requests only if no client using default routing is active on this
5009 // input: a specific app can not force routing for other apps by setting a preferred device.
5010 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005011 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5012 if (device != nullptr) {
5013 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005014 }
5015
Eric Laurentdc95a252018-04-12 12:46:56 -07005016 // If we are not in call and no client is active on this input, this methods returns
5017 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005018 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5019 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5020 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005021 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005022 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5023 device = getDeviceAndMixForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005024 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005025
Eric Laurente552edb2014-03-10 17:42:56 -07005026 return device;
5027}
5028
Eric Laurent794fde22016-03-11 09:50:45 -08005029bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5030 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005031 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005032}
5033
Eric Laurente0720872014-03-11 09:30:41 -07005034uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005035 return (uint32_t)getStrategy(stream);
5036}
5037
Eric Laurente0720872014-03-11 09:30:41 -07005038audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005039 // By checking the range of stream before calling getStrategy, we avoid
5040 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
5041 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08005042 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 return AUDIO_DEVICE_NONE;
5044 }
François Gaffie11d30102018-11-02 16:09:09 +01005045 DeviceVector activeDevices;
5046 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08005047 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
5048 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005049 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 }
Eric Laurent794fde22016-03-11 09:50:45 -08005051 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01005052 DeviceVector curDevices =
5053 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
5054 devices.merge(curDevices);
5055 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005056 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08005057 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01005058 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005059 }
5060 }
Eric Laurente552edb2014-03-10 17:42:56 -07005061 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005062
Eric Laurentb0688d62018-08-14 15:49:18 -07005063 // Favor devices selected on active streams if any to report correct device in case of
5064 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005065 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005066 devices = activeDevices;
5067 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005068 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5069 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01005070 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5071 if (!speakerSafeDevices.isEmpty()) {
5072 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5073 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005074 }
François Gaffie11d30102018-11-02 16:09:09 +01005075 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07005076}
5077
François Gaffie2110e042015-03-24 08:41:51 +01005078routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5079{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005080 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005081 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005082}
5083
Eric Laurent97ac8712018-07-27 18:59:02 -07005084routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005085 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005086 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005087 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005088 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005089 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07005090 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005091 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005092 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005093 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005094}
5095
Eric Laurente0720872014-03-11 09:30:41 -07005096void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005097 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005098 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005099 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5100 updateDevicesAndOutputs();
5101 break;
5102 default:
5103 break;
5104 }
5105}
5106
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005107uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005108
5109 // skip beacon mute management if a dedicated TTS output is available
5110 if (mTtsOutputAvailable) {
5111 return 0;
5112 }
5113
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005114 switch(event) {
5115 case STARTING_OUTPUT:
5116 mBeaconMuteRefCount++;
5117 break;
5118 case STOPPING_OUTPUT:
5119 if (mBeaconMuteRefCount > 0) {
5120 mBeaconMuteRefCount--;
5121 }
5122 break;
5123 case STARTING_BEACON:
5124 mBeaconPlayingRefCount++;
5125 break;
5126 case STOPPING_BEACON:
5127 if (mBeaconPlayingRefCount > 0) {
5128 mBeaconPlayingRefCount--;
5129 }
5130 break;
5131 }
5132
5133 if (mBeaconMuteRefCount > 0) {
5134 // any playback causes beacon to be muted
5135 return setBeaconMute(true);
5136 } else {
5137 // no other playback: unmute when beacon starts playing, mute when it stops
5138 return setBeaconMute(mBeaconPlayingRefCount == 0);
5139 }
5140}
5141
5142uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5143 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5144 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5145 // keep track of muted state to avoid repeating mute/unmute operations
5146 if (mBeaconMuted != mute) {
5147 // mute/unmute AUDIO_STREAM_TTS on all outputs
5148 ALOGV("\t muting %d", mute);
5149 uint32_t maxLatency = 0;
5150 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005151 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005152 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005153 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005154 0 /*delay*/, AUDIO_DEVICE_NONE);
5155 const uint32_t latency = desc->latency() * 2;
5156 if (latency > maxLatency) {
5157 maxLatency = latency;
5158 }
5159 }
5160 mBeaconMuted = mute;
5161 return maxLatency;
5162 }
5163 return 0;
5164}
5165
François Gaffie11d30102018-11-02 16:09:09 +01005166DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
Eric Laurent97ac8712018-07-27 18:59:02 -07005168 // Honor explicit routing requests only if all active clients have a preferred route in which
5169 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005170 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5171 if (device != nullptr) {
5172 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005173 }
5174
Eric Laurente552edb2014-03-10 17:42:56 -07005175 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005176 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5177 mDevicesForStrategy[strategy].toString().c_str());
5178 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005179 }
François Gaffie11d30102018-11-02 16:09:09 +01005180 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005181}
5182
Eric Laurente0720872014-03-11 09:30:41 -07005183void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005184{
5185 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005186 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005187 }
5188 mPreviousOutputs = mOutputs;
5189}
5190
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005191uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005192 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005193 uint32_t delayMs)
5194{
5195 // mute/unmute strategies using an incompatible device combination
5196 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5197 // if unmuting, unmute only after the specified delay
5198 if (outputDesc->isDuplicated()) {
5199 return 0;
5200 }
5201
5202 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005203 audio_devices_t deviceType = outputDesc->devices().types();
5204 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005205
5206 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005207 audio_devices_t curDeviceType =
5208 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5209 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5210 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005211 bool doMute = false;
5212
5213 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5214 doMute = true;
5215 outputDesc->mStrategyMutedByDevice[i] = true;
5216 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5217 doMute = true;
5218 outputDesc->mStrategyMutedByDevice[i] = false;
5219 }
Eric Laurent99401132014-05-07 19:48:15 -07005220 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005221 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005222 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005223 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005224 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005225 continue;
5226 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005227 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005228 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005229 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005230 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005231 if (mute) {
5232 // FIXME: should not need to double latency if volume could be applied
5233 // immediately by the audioflinger mixer. We must account for the delay
5234 // between now and the next time the audioflinger thread for this output
5235 // will process a buffer (which corresponds to one buffer size,
5236 // usually 1/2 or 1/4 of the latency).
5237 if (muteWaitMs < desc->latency() * 2) {
5238 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005239 }
5240 }
5241 }
5242 }
5243 }
5244 }
5245
Eric Laurent99401132014-05-07 19:48:15 -07005246 // temporary mute output if device selection changes to avoid volume bursts due to
5247 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005248 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005249 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5250 // temporary mute duration is conservatively set to 4 times the reported latency
5251 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5252 if (muteWaitMs < tempMuteWaitMs) {
5253 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005254 }
Eric Laurentdc462862016-07-19 12:29:53 -07005255
Eric Laurent99401132014-05-07 19:48:15 -07005256 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005257 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005258 // make sure that we do not start the temporary mute period too early in case of
5259 // delayed device change
5260 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005261 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005262 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005263 }
5264 }
5265 }
5266
Eric Laurente552edb2014-03-10 17:42:56 -07005267 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5268 if (muteWaitMs > delayMs) {
5269 muteWaitMs -= delayMs;
5270 usleep(muteWaitMs * 1000);
5271 return muteWaitMs;
5272 }
5273 return 0;
5274}
5275
François Gaffie11d30102018-11-02 16:09:09 +01005276uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5277 const DeviceVector &devices,
5278 bool force,
5279 int delayMs,
5280 audio_patch_handle_t *patchHandle,
5281 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
François Gaffie11d30102018-11-02 16:09:09 +01005283 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005284 uint32_t muteWaitMs;
5285
5286 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005287 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5288 nullptr /* patchHandle */, requiresMuteCheck);
5289 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5290 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005291 return muteWaitMs;
5292 }
Eric Laurente552edb2014-03-10 17:42:56 -07005293
5294 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005295 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Eric Laurente552edb2014-03-10 17:42:56 -07005296
François Gaffie11d30102018-11-02 16:09:09 +01005297 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5298 // output profile
5299 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5300 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5301 return 0;
5302 }
Eric Laurente552edb2014-03-10 17:42:56 -07005303
François Gaffie11d30102018-11-02 16:09:09 +01005304 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005305
François Gaffie11d30102018-11-02 16:09:09 +01005306 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5307
5308 if (!filteredDevices.isEmpty()) {
5309 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005310 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005311
5312 // if the outputs are not materially active, there is no need to mute.
5313 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005314 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005315 } else {
5316 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5317 muteWaitMs = 0;
5318 }
Eric Laurente552edb2014-03-10 17:42:56 -07005319
5320 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005321 // the requested device is AUDIO_DEVICE_NONE
5322 // OR the requested device is the same as current device
5323 // AND force is not specified
5324 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005325 // Doing this check here allows the caller to call setOutputDevices() without conditions
5326 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5327 !force && outputDesc->getPatchHandle() != 0) {
5328 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5329 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005330 return muteWaitMs;
5331 }
5332
François Gaffie11d30102018-11-02 16:09:09 +01005333 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005334
Eric Laurente552edb2014-03-10 17:42:56 -07005335 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005336 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005337 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005338 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005339 PatchBuilder patchBuilder;
5340 patchBuilder.addSource(outputDesc);
5341 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5342 for (const auto &filteredDevice : filteredDevices) {
5343 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005344 }
5345
François Gaffie11d30102018-11-02 16:09:09 +01005346 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005347 }
Eric Laurente552edb2014-03-10 17:42:56 -07005348
5349 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005350 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005351
5352 return muteWaitMs;
5353}
5354
Eric Laurentc75307b2015-03-17 15:29:32 -07005355status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005356 int delayMs,
5357 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005358{
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 ssize_t index;
5360 if (patchHandle) {
5361 index = mAudioPatches.indexOfKey(*patchHandle);
5362 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005363 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 }
5365 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 return INVALID_OPERATION;
5367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5369 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005370 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005371 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 removeAudioPatch(patchDesc->mHandle);
5373 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005374 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005375 return status;
5376}
5377
5378status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005379 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 bool force,
5381 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005382{
5383 status_t status = NO_ERROR;
5384
Eric Laurent1f2f2232014-06-02 12:01:23 -07005385 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005386 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5387 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005388
François Gaffie11d30102018-11-02 16:09:09 +01005389 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005390 PatchBuilder patchBuilder;
5391 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005392 // AUDIO_SOURCE_HOTWORD is for internal use only:
5393 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005394 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5395 auto result = usecase;
5396 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5397 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5398 }
5399 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005400 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005401 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005402 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005403 }
5404 }
5405 return status;
5406}
5407
Eric Laurent6a94d692014-05-20 11:18:06 -07005408status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5409 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005410{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005411 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005412 ssize_t index;
5413 if (patchHandle) {
5414 index = mAudioPatches.indexOfKey(*patchHandle);
5415 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005416 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005417 }
5418 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005419 return INVALID_OPERATION;
5420 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5422 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005423 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005424 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005425 removeAudioPatch(patchDesc->mHandle);
5426 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005427 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005428 return status;
5429}
5430
François Gaffie11d30102018-11-02 16:09:09 +01005431sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005432 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005433 audio_format_t& format,
5434 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005435 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005436{
5437 // Choose an input profile based on the requested capture parameters: select the first available
5438 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005439 //
5440 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5441 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005442
Glenn Kasten730b9262018-03-29 15:01:26 -07005443 sp<IOProfile> firstInexact;
5444 uint32_t updatedSamplingRate = 0;
5445 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5446 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005447 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005448 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005449 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005450 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005451 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005452 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005453 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005454 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005455 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005456 &channelMask /*updatedChannelMask*/,
5457 // FIXME ugly cast
5458 (audio_output_flags_t) flags,
5459 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 return profile;
5461 }
François Gaffie11d30102018-11-02 16:09:09 +01005462 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005463 samplingRate,
5464 &updatedSamplingRate,
5465 format,
5466 &updatedFormat,
5467 channelMask,
5468 &updatedChannelMask,
5469 // FIXME ugly cast
5470 (audio_output_flags_t) flags,
5471 false /*exactMatchRequiredForInputFlags*/)) {
5472 firstInexact = profile;
5473 }
5474
Eric Laurente552edb2014-03-10 17:42:56 -07005475 }
5476 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005477 if (firstInexact != nullptr) {
5478 samplingRate = updatedSamplingRate;
5479 format = updatedFormat;
5480 channelMask = updatedChannelMask;
5481 return firstInexact;
5482 }
Eric Laurente552edb2014-03-10 17:42:56 -07005483 return NULL;
5484}
5485
Francois Gaffie716e1432019-01-14 16:58:59 +01005486sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForAttributes(
5487 const audio_attributes_t &attributes, AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005488{
Eric Laurent97ac8712018-07-27 18:59:02 -07005489 // Honor explicit routing requests only if all active clients have a preferred route in which
5490 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005491 sp<DeviceDescriptor> device =
Francois Gaffie716e1432019-01-14 16:58:59 +01005492 findPreferredDevice(mInputs, attributes.source, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005493 if (device != nullptr) {
5494 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005495 }
5496
François Gaffie11d30102018-11-02 16:09:09 +01005497 sp<DeviceDescriptor> selectedDeviceFromMix =
Francois Gaffie716e1432019-01-14 16:58:59 +01005498 mPolicyMixes.getDeviceAndMixForInputSource(attributes.source, mAvailableInputDevices,
François Gaffie11d30102018-11-02 16:09:09 +01005499 policyMix);
5500 return (selectedDeviceFromMix != nullptr) ?
Francois Gaffie716e1432019-01-14 16:58:59 +01005501 selectedDeviceFromMix : getDeviceForAttributes(attributes);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005502}
5503
Francois Gaffie716e1432019-01-14 16:58:59 +01005504sp<DeviceDescriptor> AudioPolicyManager::getDeviceForAttributes(const audio_attributes_t &attributes)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005505{
Francois Gaffie716e1432019-01-14 16:58:59 +01005506 audio_devices_t device = mEngine->getDeviceForInputSource(attributes.source);
5507 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
5508 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
5509 return mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005510 String8(attributes.tags + strlen("addr=")),
5511 AUDIO_FORMAT_DEFAULT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005512 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005513 return mAvailableInputDevices.getDevice(device, String8(), AUDIO_FORMAT_DEFAULT);
Eric Laurente552edb2014-03-10 17:42:56 -07005514}
5515
Eric Laurente0720872014-03-11 09:30:41 -07005516float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005517 int index,
5518 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005520 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005521
5522 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5523 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5524 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5525 // the ringtone volume
5526 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5527 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5528 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5529 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5530 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5531 }
5532
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005533 // in-call: always cap volume by voice volume + some low headroom
5534 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005535 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005536 switch (stream) {
5537 case AUDIO_STREAM_SYSTEM:
5538 case AUDIO_STREAM_RING:
5539 case AUDIO_STREAM_MUSIC:
5540 case AUDIO_STREAM_ALARM:
5541 case AUDIO_STREAM_NOTIFICATION:
5542 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5543 case AUDIO_STREAM_DTMF:
5544 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005545 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005546 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005547 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005548 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005549 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005550 if (volumeDB > maxVoiceVolDb) {
5551 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5552 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5553 volumeDB = maxVoiceVolDb;
5554 }
5555 } break;
5556 default:
5557 break;
5558 }
5559 }
5560
Eric Laurente552edb2014-03-10 17:42:56 -07005561 // if a headset is connected, apply the following rules to ring tones and notifications
5562 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005563 // - always attenuate notifications volume by 6dB
5564 // - attenuate ring tones volume by 6dB unless music is not playing and
5565 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005566 // - if music is playing, always limit the volume to current music volume,
5567 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005568 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005569 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5570 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5571 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005572 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005573 AUDIO_DEVICE_OUT_USB_HEADSET |
5574 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005575 ((stream_strategy == STRATEGY_SONIFICATION)
5576 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005577 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005578 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005579 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005580 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005581 // when the phone is ringing we must consider that music could have been paused just before
5582 // by the music application and behave as if music was active if the last music track was
5583 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005584 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005585 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005586 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005587 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005588 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005589 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5590 musicDevice),
5591 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005592 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5593 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005594 if (volumeDB > minVolDB) {
5595 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005596 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005597 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005598 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5599 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5600 // on A2DP, also ensure notification volume is not too low compared to media when
5601 // intended to be played
5602 if ((volumeDB > -96.0f) &&
5603 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5604 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5605 stream, device,
5606 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5607 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5608 }
5609 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005610 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5611 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005612 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005613 }
5614 }
5615
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005616 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005617}
5618
Eric Laurent3839bc02018-07-10 18:33:34 -07005619int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5620 audio_stream_type_t srcStream,
5621 audio_stream_type_t dstStream)
5622{
5623 if (srcStream == dstStream) {
5624 return srcIndex;
5625 }
5626 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5627 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5628 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5629 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5630
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005631 // preserve mute request or correct range
5632 if (srcIndex < minSrc) {
5633 if (srcIndex == 0) {
5634 return 0;
5635 }
5636 srcIndex = minSrc;
5637 } else if (srcIndex > maxSrc) {
5638 srcIndex = maxSrc;
5639 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005640 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5641}
5642
Eric Laurente0720872014-03-11 09:30:41 -07005643status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005644 int index,
5645 const sp<AudioOutputDescriptor>& outputDesc,
5646 audio_devices_t device,
5647 int delayMs,
5648 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005649{
Eric Laurente552edb2014-03-10 17:42:56 -07005650 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005651 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005652 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005653 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005654 return NO_ERROR;
5655 }
François Gaffie2110e042015-03-24 08:41:51 +01005656 audio_policy_forced_cfg_t forceUseForComm =
5657 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005658 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005659 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5660 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005661 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005662 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005663 return INVALID_OPERATION;
5664 }
5665
Eric Laurentc75307b2015-03-17 15:29:32 -07005666 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005667 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005668 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005669
Eric Laurentffbc80f2015-03-18 18:30:19 -07005670 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005671 if (outputDesc->isFixedVolume(device) ||
5672 // Force VoIP volume to max for bluetooth SCO
5673 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5674 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005675 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005676 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005677
Eric Laurentffbc80f2015-03-18 18:30:19 -07005678 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005679
Eric Laurent3b73df72014-03-11 09:06:29 -07005680 if (stream == AUDIO_STREAM_VOICE_CALL ||
5681 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005682 float voiceVolume;
5683 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005684 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005685 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005686 } else {
5687 voiceVolume = 1.0;
5688 }
5689
Eric Laurent18fba842016-03-31 14:41:26 -07005690 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005691 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5692 mLastVoiceVolume = voiceVolume;
5693 }
5694 }
5695
5696 return NO_ERROR;
5697}
5698
Eric Laurentc75307b2015-03-17 15:29:32 -07005699void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5700 audio_devices_t device,
5701 int delayMs,
5702 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005703{
Eric Laurentc75307b2015-03-17 15:29:32 -07005704 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005705
Eric Laurent794fde22016-03-11 09:50:45 -08005706 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005707 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005708 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005709 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005710 device,
5711 delayMs,
5712 force);
5713 }
5714}
5715
Eric Laurente0720872014-03-11 09:30:41 -07005716void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005717 bool on,
5718 const sp<AudioOutputDescriptor>& outputDesc,
5719 int delayMs,
5720 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005721{
Eric Laurent72249d52015-06-08 11:12:15 -07005722 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5723 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005724 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005725 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005726 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005727 }
5728 }
5729}
5730
Eric Laurente0720872014-03-11 09:30:41 -07005731void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005732 bool on,
5733 const sp<AudioOutputDescriptor>& outputDesc,
5734 int delayMs,
5735 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005736{
Eric Laurente552edb2014-03-10 17:42:56 -07005737 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005738 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005739 }
5740
Eric Laurentc75307b2015-03-17 15:29:32 -07005741 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5742 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005743
5744 if (on) {
5745 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005746 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005747 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005748 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005749 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005750 }
5751 }
5752 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5753 outputDesc->mMuteCount[stream]++;
5754 } else {
5755 if (outputDesc->mMuteCount[stream] == 0) {
5756 ALOGV("setStreamMute() unmuting non muted stream!");
5757 return;
5758 }
5759 if (--outputDesc->mMuteCount[stream] == 0) {
5760 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005761 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005762 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005763 device,
5764 delayMs);
5765 }
5766 }
5767}
5768
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005769audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5770{
5771 // flags to stream type mapping
5772 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5773 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5774 }
5775 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5776 return AUDIO_STREAM_BLUETOOTH_SCO;
5777 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005778 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5779 return AUDIO_STREAM_TTS;
5780 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005781
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005782 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005783}
Eric Laurente83b55d2014-11-14 10:06:21 -08005784
François Gaffie53615e22015-03-19 09:24:12 +01005785bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5786{
Eric Laurente83b55d2014-11-14 10:06:21 -08005787 // has flags that map to a strategy?
5788 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5789 return true;
5790 }
5791
5792 // has known usage?
5793 switch (paa->usage) {
5794 case AUDIO_USAGE_UNKNOWN:
5795 case AUDIO_USAGE_MEDIA:
5796 case AUDIO_USAGE_VOICE_COMMUNICATION:
5797 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5798 case AUDIO_USAGE_ALARM:
5799 case AUDIO_USAGE_NOTIFICATION:
5800 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5801 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5802 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5803 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5804 case AUDIO_USAGE_NOTIFICATION_EVENT:
5805 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5806 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5807 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5808 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005809 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005810 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005811 break;
5812 default:
5813 return false;
5814 }
5815 return true;
5816}
5817
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005818bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005819 routing_strategy strategy, uint32_t inPastMs,
5820 nsecs_t sysTime) const
5821{
5822 if ((sysTime == 0) && (inPastMs != 0)) {
5823 sysTime = systemTime();
5824 }
Eric Laurent794fde22016-03-11 09:50:45 -08005825 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005826 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005827 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005828 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5829 return true;
5830 }
5831 }
5832 return false;
5833}
5834
François Gaffie11d30102018-11-02 16:09:09 +01005835bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5836 routing_strategy strategy, uint32_t inPastMs,
5837 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005838{
5839 for (size_t i = 0; i < mOutputs.size(); i++) {
5840 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5841 if (outputDesc->sharesHwModuleWith(desc)
5842 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5843 return true;
5844 }
5845 }
5846 return false;
5847}
5848
François Gaffie2110e042015-03-24 08:41:51 +01005849audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5850{
5851 return mEngine->getForceUse(usage);
5852}
5853
5854bool AudioPolicyManager::isInCall()
5855{
5856 return isStateInCall(mEngine->getPhoneState());
5857}
5858
5859bool AudioPolicyManager::isStateInCall(int state)
5860{
5861 return is_state_in_call(state);
5862}
5863
Eric Laurentd60560a2015-04-10 11:31:20 -07005864void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5865{
5866 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005867 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5868 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5869 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5870 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005871 }
5872 }
5873
5874 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5875 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5876 bool release = false;
5877 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5878 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5879 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5880 source->ext.device.type == deviceDesc->type()) {
5881 release = true;
5882 }
5883 }
5884 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5885 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5886 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5887 sink->ext.device.type == deviceDesc->type()) {
5888 release = true;
5889 }
5890 }
5891 if (release) {
5892 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5893 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5894 }
5895 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005896
5897 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005898}
5899
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005900void AudioPolicyManager::modifySurroundFormats(
5901 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005902 std::unordered_set<audio_format_t> enforcedSurround(
5903 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005904 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5905 for (const auto& pair : mConfig.getSurroundFormats()) {
5906 allSurround.insert(pair.first);
5907 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5908 }
Phil Burk09bc4612016-02-24 15:58:15 -08005909
5910 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5911 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005912 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005913 // This is the resulting set of formats depending on the surround mode:
5914 // 'all surround' = allSurround
5915 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5916 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5917 // 'manual surround' = mManualSurroundFormats
5918 // AUTO: formats v 'enforced surround'
5919 // ALWAYS: formats v 'all surround' v 'enforced surround'
5920 // NEVER: formats ^ 'non-surround'
5921 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005922
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005923 std::unordered_set<audio_format_t> formatSet;
5924 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5925 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005926 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005927 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005928 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005929 formatSet.insert(*formatIter);
5930 }
5931 }
5932 } else {
5933 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5934 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005935 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005936
jiabin81772902018-04-02 17:52:27 -07005937 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005938 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005939 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5940 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5941 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005942 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005943 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5944 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5945 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005946 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005947 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005948 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005949 for (const auto& format : formatSet) {
5950 formatsPtr->push(format);
5951 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005952}
5953
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005954void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005955 ChannelsVector &channelMasks = *channelMasksPtr;
5956 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5957 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5958
5959 // If NEVER, then remove support for channelMasks > stereo.
5960 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5961 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5962 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5963 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5964 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5965 channelMasks.removeAt(maskIndex);
5966 } else {
5967 maskIndex++;
5968 }
5969 }
jiabin81772902018-04-02 17:52:27 -07005970 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5971 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5972 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005973 bool supports5dot1 = false;
5974 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005975 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005976 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5977 supports5dot1 = true;
5978 break;
5979 }
5980 }
5981 // If not then add 5.1 support.
5982 if (!supports5dot1) {
5983 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005984 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005985 }
Phil Burk09bc4612016-02-24 15:58:15 -08005986 }
5987}
5988
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005989void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005990 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005991 AudioProfileVector &profiles)
5992{
5993 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005994 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005995
François Gaffie112b0af2015-11-19 16:13:25 +01005996 // Format MUST be checked first to update the list of AudioProfile
5997 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005998 reply = mpClientInterface->getParameters(
5999 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006000 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006001 AudioParameter repliedParameters(reply);
6002 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006003 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006004 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6005 return;
6006 }
Phil Burk09bc4612016-02-24 15:58:15 -08006007 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006008 if (device == AUDIO_DEVICE_OUT_HDMI
6009 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006010 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006011 }
Phil Burk09bc4612016-02-24 15:58:15 -08006012 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006013 }
François Gaffie112b0af2015-11-19 16:13:25 +01006014
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006015 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006016 ChannelsVector channelMasks;
6017 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006018 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006019 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006020
6021 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006022 reply = mpClientInterface->getParameters(
6023 ioHandle,
6024 requestedParameters.toString() + ";" +
6025 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006026 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006027 AudioParameter repliedParameters(reply);
6028 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006029 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006030 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006031 }
6032 }
6033 if (profiles.hasDynamicChannelsFor(format)) {
6034 reply = mpClientInterface->getParameters(ioHandle,
6035 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006036 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006037 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006038 AudioParameter repliedParameters(reply);
6039 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006040 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006041 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006042 if (device == AUDIO_DEVICE_OUT_HDMI
6043 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006044 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006045 }
François Gaffie112b0af2015-11-19 16:13:25 +01006046 }
6047 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006048 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006049 }
6050}
Eric Laurentd60560a2015-04-10 11:31:20 -07006051
Mikhail Naganovdc769682018-05-04 15:34:08 -07006052status_t AudioPolicyManager::installPatch(const char *caller,
6053 audio_patch_handle_t *patchHandle,
6054 AudioIODescriptorInterface *ioDescriptor,
6055 const struct audio_patch *patch,
6056 int delayMs)
6057{
6058 ssize_t index = mAudioPatches.indexOfKey(
6059 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6060 *patchHandle : ioDescriptor->getPatchHandle());
6061 sp<AudioPatch> patchDesc;
6062 status_t status = installPatch(
6063 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6064 if (status == NO_ERROR) {
6065 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6066 }
6067 return status;
6068}
6069
6070status_t AudioPolicyManager::installPatch(const char *caller,
6071 ssize_t index,
6072 audio_patch_handle_t *patchHandle,
6073 const struct audio_patch *patch,
6074 int delayMs,
6075 uid_t uid,
6076 sp<AudioPatch> *patchDescPtr)
6077{
6078 sp<AudioPatch> patchDesc;
6079 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6080 if (index >= 0) {
6081 patchDesc = mAudioPatches.valueAt(index);
6082 afPatchHandle = patchDesc->mAfPatchHandle;
6083 }
6084
6085 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6086 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6087 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6088 if (status == NO_ERROR) {
6089 if (index < 0) {
6090 patchDesc = new AudioPatch(patch, uid);
6091 addAudioPatch(patchDesc->mHandle, patchDesc);
6092 } else {
6093 patchDesc->mPatch = *patch;
6094 }
6095 patchDesc->mAfPatchHandle = afPatchHandle;
6096 if (patchHandle) {
6097 *patchHandle = patchDesc->mHandle;
6098 }
6099 nextAudioPortGeneration();
6100 mpClientInterface->onAudioPatchListUpdate();
6101 }
6102 if (patchDescPtr) *patchDescPtr = patchDesc;
6103 return status;
6104}
6105
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006106} // namespace android