blob: f39614ec572adbab54492ab7b04c14d5c140b792 [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"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110034#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070035
François Gaffie2110e042015-03-24 08:41:51 +010036#include <AudioPolicyManagerInterface.h>
37#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070040#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080041#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
Mikhail Naganov15be9d22017-11-08 14:18:13 +110065// Compressed formats for MSD module, ordered from most preferred to least preferred.
66static const std::vector<audio_format_t> compressedFormatsOrder = {{
67 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
68 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
69// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
70static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
71 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
72 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
73 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
74
Eric Laurente552edb2014-03-10 17:42:56 -070075// ----------------------------------------------------------------------------
76// AudioPolicyInterface implementation
77// ----------------------------------------------------------------------------
78
Eric Laurente0720872014-03-11 09:30:41 -070079status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080080 audio_policy_dev_state_t state,
81 const char *device_address,
82 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070083{
jiabina7b43792018-02-15 16:04:46 -080084 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
85 nextAudioPortGeneration();
86 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080087}
88
François Gaffie44481e72016-04-20 07:49:57 +020089void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
90 audio_policy_dev_state_t state,
91 const String8 &device_address)
92{
93 AudioParameter param(device_address);
94 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070095 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020096 param.addInt(key, device);
97 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
98}
99
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800101 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800102 const char *device_address,
103 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800104{
Paul McLeane743a472015-01-28 11:07:31 -0800105 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800106 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700107
108 // connect/disconnect only 1 device at a time
109 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
110
François Gaffie53615e22015-03-19 09:24:12 +0100111 sp<DeviceDescriptor> devDesc =
112 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800113
Eric Laurente552edb2014-03-10 17:42:56 -0700114 // handle output devices
115 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700116 SortedVector <audio_io_handle_t> outputs;
117
Eric Laurent3a4311c2014-03-17 12:00:47 -0700118 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
119
Eric Laurente552edb2014-03-10 17:42:56 -0700120 // save a copy of the opened output descriptors before any output is opened or closed
121 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
122 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700123 switch (state)
124 {
125 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800126 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700128 ALOGW("setDeviceConnectionState() device already connected: %x", device);
129 return INVALID_OPERATION;
130 }
131 ALOGV("setDeviceConnectionState() connecting device %x", device);
132
Eric Laurente552edb2014-03-10 17:42:56 -0700133 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700134 index = mAvailableOutputDevices.add(devDesc);
135 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100136 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700137 if (module == 0) {
138 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
139 device);
140 mAvailableOutputDevices.remove(devDesc);
141 return INVALID_OPERATION;
142 }
Paul McLeane743a472015-01-28 11:07:31 -0800143 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 } else {
145 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700146 }
147
François Gaffie44481e72016-04-20 07:49:57 +0200148 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
149 // parameters on newly connected devices (instead of opening the outputs...)
150 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
151
Eric Laurenta1d525f2015-01-29 13:36:45 -0800152 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700153 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200154
155 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
156 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700157 return INVALID_OPERATION;
158 }
François Gaffie2110e042015-03-24 08:41:51 +0100159 // Propagate device availability to Engine
160 mEngine->setDeviceConnectionState(devDesc, state);
161
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700162 // outputs should never be empty here
163 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
164 "checkOutputsForDevice() returned no outputs but status OK");
165 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
166 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800167
Eric Laurent3ae5f312015-02-03 17:12:08 -0800168 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700169 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700170 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700172 ALOGW("setDeviceConnectionState() device not connected: %x", device);
173 return INVALID_OPERATION;
174 }
175
Paul McLean5c477aa2014-08-20 16:47:57 -0700176 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
177
Paul McLeane743a472015-01-28 11:07:31 -0800178 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200179 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700180
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700182 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700183
Eric Laurenta1d525f2015-01-29 13:36:45 -0800184 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100185
186 // Propagate device availability to Engine
187 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700188 } break;
189
190 default:
191 ALOGE("setDeviceConnectionState() invalid state: %x", state);
192 return BAD_VALUE;
193 }
194
Mikhail Naganov37977152018-07-11 15:54:44 -0700195 checkForDeviceAndOutputChanges([&]() {
196 // outputs must be closed after checkOutputForAllStrategies() is executed
197 if (!outputs.isEmpty()) {
198 for (audio_io_handle_t output : outputs) {
199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
200 // close unused outputs after device disconnection or direct outputs that have been
201 // opened by checkOutputsForDevice() to query dynamic parameters
202 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
203 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
204 (desc->mDirectOpenCount == 0))) {
205 closeOutput(output);
206 }
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
209 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700211 return false;
212 });
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent87ffa392015-05-22 10:32:38 -0700214 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700215 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
216 updateCallRouting(newDevice);
217 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100218 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700219 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700220 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
221 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
222 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700223 // do not force device change on duplicated output because if device is 0, it will
224 // also force a device 0 for the two outputs it is duplicated to which may override
225 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100226 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
227 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100228 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700229 // always force when disconnecting (a non-duplicated device)
230 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700231 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 }
Eric Laurente552edb2014-03-10 17:42:56 -0700233 }
234
Eric Laurentd60560a2015-04-10 11:31:20 -0700235 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
236 cleanUpForDevice(devDesc);
237 }
238
Eric Laurent72aa32f2014-05-30 18:51:48 -0700239 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700240 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700241 } // end if is output device
242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // handle input devices
244 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700245 SortedVector <audio_io_handle_t> inputs;
246
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %d", device);
254 return INVALID_OPERATION;
255 }
François Gaffie53615e22015-03-19 09:24:12 +0100256 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700257 if (module == NULL) {
258 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
259 device);
260 return INVALID_OPERATION;
261 }
François Gaffie44481e72016-04-20 07:49:57 +0200262
263 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
264 // parameters on newly connected devices (instead of opening the inputs...)
265 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
266
Paul McLean9080a4c2015-06-18 08:24:02 -0700267 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200268 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
269 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700270 return INVALID_OPERATION;
271 }
272
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 index = mAvailableInputDevices.add(devDesc);
274 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800275 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 } else {
277 return NO_MEMORY;
278 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800279
François Gaffie2110e042015-03-24 08:41:51 +0100280 // Propagate device availability to Engine
281 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700282 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700283
284 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %d", device);
288 return INVALID_OPERATION;
289 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700290
291 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
292
293 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200294 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700295
Paul McLean9080a4c2015-06-18 08:24:02 -0700296 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700297 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
François Gaffie2110e042015-03-24 08:41:51 +0100299 // Propagate device availability to Engine
300 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700301 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700302
303 default:
304 ALOGE("setDeviceConnectionState() invalid state: %x", state);
305 return BAD_VALUE;
306 }
307
Eric Laurentd4692962014-05-05 18:13:44 -0700308 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700309 // As the input device list can impact the output device selection, update
310 // getDeviceForStrategy() cache
311 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700312
Eric Laurent87ffa392015-05-22 10:32:38 -0700313 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700314 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
315 updateCallRouting(newDevice);
316 }
317
Eric Laurentd60560a2015-04-10 11:31:20 -0700318 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
319 cleanUpForDevice(devDesc);
320 }
321
Eric Laurentb52c1522014-05-20 11:27:36 -0700322 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700323 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700324 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700325
326 ALOGW("setDeviceConnectionState() invalid device: %x", device);
327 return BAD_VALUE;
328}
329
Eric Laurente0720872014-03-11 09:30:41 -0700330audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100331 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700332{
Eric Laurent634b7142016-04-20 13:48:02 -0700333 sp<DeviceDescriptor> devDesc =
334 mHwModules.getDeviceDescriptor(device, device_address, "",
335 (strlen(device_address) != 0)/*matchAddress*/);
336
337 if (devDesc == 0) {
338 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
339 device, device_address);
340 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
341 }
François Gaffie53615e22015-03-19 09:24:12 +0100342
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 DeviceVector *deviceVector;
344
Eric Laurente552edb2014-03-10 17:42:56 -0700345 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700347 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 deviceVector = &mAvailableInputDevices;
349 } else {
350 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
351 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700352 }
Eric Laurent634b7142016-04-20 13:48:02 -0700353
354 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
355 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800356}
357
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800358status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
359 const char *device_address,
360 const char *device_name)
361{
362 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700363 String8 reply;
364 AudioParameter param;
365 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366
367 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
368 device, device_address, device_name);
369
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800370 // connect/disconnect only 1 device at a time
371 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
372
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800373 // Check if the device is currently connected
374 sp<DeviceDescriptor> devDesc =
375 mHwModules.getDeviceDescriptor(device, device_address, device_name);
376 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
377 if (index < 0) {
378 // Nothing to do: device is not connected
379 return NO_ERROR;
380 }
381
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700382 // For offloaded A2DP, Hw modules may have the capability to
383 // configure codecs. Check if any of the loaded hw modules
384 // supports this.
385 // If supported, send a set parameter to configure A2DP codecs
386 // and return. No need to toggle device state.
387 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
388 reply = mpClientInterface->getParameters(
389 AUDIO_IO_HANDLE_NONE,
390 String8(AudioParameter::keyReconfigA2dpSupported));
391 AudioParameter repliedParameters(reply);
392 repliedParameters.getInt(
393 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
394 if (isReconfigA2dpSupported) {
395 const String8 key(AudioParameter::keyReconfigA2dp);
396 param.add(key, String8("true"));
397 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
398 return NO_ERROR;
399 }
400 }
401
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800402 // Toggle the device state: UNAVAILABLE -> AVAILABLE
403 // This will force reading again the device configuration
404 status = setDeviceConnectionState(device,
405 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
406 device_address, device_name);
407 if (status != NO_ERROR) {
408 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
409 status);
410 return status;
411 }
412
413 status = setDeviceConnectionState(device,
414 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
415 device_address, device_name);
416 if (status != NO_ERROR) {
417 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
418 status);
419 return status;
420 }
421
422 return NO_ERROR;
423}
424
Eric Laurentdc462862016-07-19 12:29:53 -0700425uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700426{
427 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700428 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429
Andy Hunga76c7de2016-12-13 19:14:31 -0800430 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700431 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700432 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800433 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
435
436 // release existing RX patch if any
437 if (mCallRxPatch != 0) {
438 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
439 mCallRxPatch.clear();
440 }
441 // release TX patch if any
442 if (mCallTxPatch != 0) {
443 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
444 mCallTxPatch.clear();
445 }
446
447 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
448 // via setOutputDevice() on primary output.
449 // Otherwise, create two audio patches for TX and RX path.
450 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700451 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 // If the TX device is also on the primary HW module, setOutputDevice() will take care
453 // of it due to legacy implementation. If not, create a patch.
454 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
455 == AUDIO_DEVICE_NONE) {
456 createTxPatch = true;
457 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700458 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800459 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 createTxPatch = true;
461 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700462 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800463 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 return muteWaitMs;
467}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
470 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700471 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800473 sp<DeviceDescriptor> txSourceDeviceDesc;
474 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700475 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
476 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
479 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 }
481
482 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
483 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
484 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
485 // request to reuse existing output stream if one is already opened to reach the target device
486 if (output != AUDIO_IO_HANDLE_NONE) {
487 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
488 ALOG_ASSERT(!outputDesc->isDuplicated(),
489 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700490 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800491 }
492
493 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700494 // terminate active capture if on the same HW module as the call TX source device
495 // FIXME: would be better to refine to only inputs whose profile connects to the
496 // call TX device but this information is not in the audio patch and logic here must be
497 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800498 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800499 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700500 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700501 }
502 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700503 }
Eric Laurentdc462862016-07-19 12:29:53 -0700504
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800505 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700506 status_t status = mpClientInterface->createAudioPatch(
507 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 ALOGW_IF(status != NO_ERROR,
509 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
510 sp<AudioPatch> audioPatch;
511 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700512 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 audioPatch->mAfPatchHandle = afPatchHandle;
514 audioPatch->mUid = mUidCached;
515 }
516 return audioPatch;
517}
518
Mikhail Naganovdc769682018-05-04 15:34:08 -0700519sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100520 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700521 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800522 ALOG_ASSERT(!deviceList.isEmpty(),
523 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700524 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700525}
526
Eric Laurente0720872014-03-11 09:30:41 -0700527void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700528{
529 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100530 // store previous phone state for management of sonification strategy below
531 int oldState = mEngine->getPhoneState();
532
533 if (mEngine->setPhoneState(state) != NO_ERROR) {
534 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700535 return;
536 }
François Gaffie2110e042015-03-24 08:41:51 +0100537 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700538 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800541 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
543
François Gaffie2110e042015-03-24 08:41:51 +0100544 /**
545 * Switching to or from incall state or switching between telephony and VoIP lead to force
546 * routing command.
547 */
548 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
549 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700550
551 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700552 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700553
Eric Laurente552edb2014-03-10 17:42:56 -0700554 int delayMs = 0;
555 if (isStateInCall(state)) {
556 nsecs_t sysTime = systemTime();
557 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 // mute media and sonification strategies and delay device switch by the largest
560 // latency of any output where either strategy is active.
561 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100562 if ((isStrategyActive(desc, STRATEGY_MEDIA,
563 SONIFICATION_HEADSET_MUSIC_DELAY,
564 sysTime) ||
565 isStrategyActive(desc, STRATEGY_SONIFICATION,
566 SONIFICATION_HEADSET_MUSIC_DELAY,
567 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700568 (delayMs < (int)desc->latency()*2)) {
569 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700571 setStrategyMute(STRATEGY_MEDIA, true, desc);
572 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700573 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700574 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
575 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700576 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
577 }
578 }
579
Eric Laurent87ffa392015-05-22 10:32:38 -0700580 if (hasPrimaryOutput()) {
581 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
582 // the device returned is not necessarily reachable via this output
583 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
584 // force routing command to audio hardware when ending call
585 // even if no device change is needed
586 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
587 rxDevice = mPrimaryOutput->device();
588 }
Eric Laurente552edb2014-03-10 17:42:56 -0700589
Eric Laurent87ffa392015-05-22 10:32:38 -0700590 if (state == AUDIO_MODE_IN_CALL) {
591 updateCallRouting(rxDevice, delayMs);
592 } else if (oldState == AUDIO_MODE_IN_CALL) {
593 if (mCallRxPatch != 0) {
594 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
595 mCallRxPatch.clear();
596 }
597 if (mCallTxPatch != 0) {
598 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
599 mCallTxPatch.clear();
600 }
601 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
602 } else {
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700606
607 // reevaluate routing on all outputs in case tracks have been started during the call
608 for (size_t i = 0; i < mOutputs.size(); i++) {
609 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
610 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
611 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800612 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700613 }
614 }
615
Eric Laurente552edb2014-03-10 17:42:56 -0700616 if (isStateInCall(state)) {
617 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700618 // force reevaluating accessibility routing when call starts
619 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621
622 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 if (state == AUDIO_MODE_RINGTONE &&
624 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700625 mLimitRingtoneVolume = true;
626 } else {
627 mLimitRingtoneVolume = false;
628 }
629}
630
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700631audio_mode_t AudioPolicyManager::getPhoneState() {
632 return mEngine->getPhoneState();
633}
634
Eric Laurente0720872014-03-11 09:30:41 -0700635void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700637{
François Gaffie2110e042015-03-24 08:41:51 +0100638 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700639 if (config == mEngine->getForceUse(usage)) {
640 return;
641 }
Eric Laurente552edb2014-03-10 17:42:56 -0700642
François Gaffie2110e042015-03-24 08:41:51 +0100643 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
644 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
645 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700646 }
François Gaffie2110e042015-03-24 08:41:51 +0100647 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
648 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
649 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700650
651 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700652 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800653
Eric Laurentdc462862016-07-19 12:29:53 -0700654 //FIXME: workaround for truncated touch sounds
655 // to be removed when the problem is handled by system UI
656 uint32_t delayMs = 0;
657 uint32_t waitMs = 0;
658 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
659 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
660 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700663 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 }
Eric Laurente552edb2014-03-10 17:42:56 -0700665 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
667 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
668 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700669 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
670 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 }
Eric Laurente552edb2014-03-10 17:42:56 -0700672 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700673 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700674 }
675 }
676
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800677 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800678 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700679 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800680 if (activeDesc->mProfile->getSupportedDevices().types() &
681 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
682 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700683 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800684 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687}
688
Eric Laurente0720872014-03-11 09:30:41 -0700689void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700690{
691 ALOGV("setSystemProperty() property %s, value %s", property, value);
692}
693
694// Find a direct output profile compatible with the parameters passed, even if the input flags do
695// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800696sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700697 audio_devices_t device,
698 uint32_t samplingRate,
699 audio_format_t format,
700 audio_channel_mask_t channelMask,
701 audio_output_flags_t flags)
702{
Eric Laurent861a6282015-05-18 15:40:16 -0700703 // only retain flags that will drive the direct output profile selection
704 // if explicitly requested
705 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700706 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
707 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700708 flags =
709 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
710
711 sp<IOProfile> profile;
712
Mikhail Naganovd4120142017-12-06 15:49:22 -0800713 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800714 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700715 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700716 samplingRate, NULL /*updatedSamplingRate*/,
717 format, NULL /*updatedFormat*/,
718 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700719 flags)) {
720 continue;
721 }
722 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100723 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700724 continue;
725 }
726 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100727 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700728 continue;
729 }
730 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700733 }
Eric Laurente552edb2014-03-10 17:42:56 -0700734 }
735 }
Eric Laurent861a6282015-05-18 15:40:16 -0700736 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700737}
738
Eric Laurentf4e63452017-11-06 19:31:46 +0000739audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700740{
Eric Laurent3b73df72014-03-11 09:06:29 -0700741 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800743
744 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
745 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
746 // format, flags, etc. This may result in some discrepancy for functions that utilize
747 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
748 // and AudioSystem::getOutputSamplingRate().
749
Eric Laurentf4e63452017-11-06 19:31:46 +0000750 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
751 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700752
Eric Laurentf4e63452017-11-06 19:31:46 +0000753 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
754 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700755}
756
Eric Laurente83b55d2014-11-14 10:06:21 -0800757status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
758 audio_io_handle_t *output,
759 audio_session_t session,
760 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700761 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800762 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200763 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700764 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800765 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700766{
Eric Laurente83b55d2014-11-14 10:06:21 -0800767 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700768 DeviceVector outputDevices;
769 routing_strategy strategy;
770 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700771 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100772 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700773
Eric Laurent8f42ea12018-08-08 09:08:25 -0700774 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
775 if (*portId != AUDIO_PORT_HANDLE_NONE) {
776 return INVALID_OPERATION;
777 }
778
Eric Laurente83b55d2014-11-14 10:06:21 -0800779 if (attr != NULL) {
780 if (!isValidAttributes(attr)) {
781 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
782 attr->usage, attr->content_type, attr->flags,
783 attr->tags);
784 return BAD_VALUE;
785 }
786 attributes = *attr;
787 } else {
788 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
789 ALOGE("getOutputForAttr(): invalid stream type");
790 return BAD_VALUE;
791 }
792 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800794
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700795 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700796 " session %d selectedDeviceId %d",
797 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
798 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700799
Eric Laurent97ac8712018-07-27 18:59:02 -0700800 *stream = streamTypefromAttributesInt(&attributes);
801
802 strategy = getStrategyForAttr(&attributes);
803
Scott Randolph7b1fd232018-06-18 15:33:03 -0700804 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700805 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
806 sp<DeviceDescriptor> deviceDesc =
807 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
808 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700809 } else {
810 // If no explict route, is there a matching dynamic policy that applies?
811 sp<SwAudioOutputDescriptor> desc;
812 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
813 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
814 if (!audio_has_proportional_frames(config->format)) {
815 return BAD_VALUE;
816 }
817 *stream = streamTypefromAttributesInt(&attributes);
818 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700819 AudioMix *mix = desc->mPolicyMix;
820 sp<DeviceDescriptor> deviceDesc =
821 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
822 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700823 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700824 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700825 }
826
827 // Virtual sources must always be dynamicaly or explicitly routed
828 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
829 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
830 return BAD_VALUE;
831 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700832 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700834
Eric Laurente83b55d2014-11-14 10:06:21 -0800835 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200836 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700837 }
838
Nadav Barb2f18162018-07-18 13:01:53 +0300839 // Set incall music only if device was explicitly set, and fallback to the device which is
840 // chosen by the engine if not.
841 // FIXME: provide a more generic approach which is not device specific and move this back
842 // to getOutputForDevice.
843 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
844 *stream == AUDIO_STREAM_MUSIC &&
845 audio_is_linear_pcm(config->format) &&
846 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700847 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300848 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
849 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700850 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300851 device = mEngine->getDeviceForStrategy(strategy);
852 }
853 }
854
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800855 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
856 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200857 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100859 *output = AUDIO_IO_HANDLE_NONE;
860 if (msdDevice != AUDIO_DEVICE_NONE) {
861 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
862 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
863 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
864 __func__, msdDevice, device);
865 device = msdDevice;
866 } else {
867 *output = AUDIO_IO_HANDLE_NONE;
868 }
869 }
870 if (*output == AUDIO_IO_HANDLE_NONE) {
871 *output = getOutputForDevice(device, session, *stream, config, flags);
872 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800873 if (*output == AUDIO_IO_HANDLE_NONE) {
874 return INVALID_OPERATION;
875 }
Paul McLeanaa981192015-03-21 09:55:15 -0700876
Eric Laurent8fc147b2018-07-22 19:13:55 -0700877 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700878 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
879 : AUDIO_PORT_HANDLE_NONE;
880
Eric Laurent8fc147b2018-07-22 19:13:55 -0700881exit:
882 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
883 .format = config->format,
884 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700885 *portId = AudioPort::getNextUniqueId();
886
Eric Laurent8fc147b2018-07-22 19:13:55 -0700887 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700888 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
889 requestedDeviceId, *stream,
890 getStrategyForAttr(&attributes),
891 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700892 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700893 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700894
895 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
896 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700897
Eric Laurente83b55d2014-11-14 10:06:21 -0800898 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
901audio_io_handle_t AudioPolicyManager::getOutputForDevice(
902 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800903 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800905 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200906 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907{
Andy Hungc88b0642018-04-27 15:42:35 -0700908 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700909 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700910
Eric Laurente552edb2014-03-10 17:42:56 -0700911 // open a direct output if required by specified parameters
912 //force direct flag if offload flag is set: offloading implies a direct output stream
913 // and all common behaviors are driven by checking only the direct flag
914 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200915 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
916 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700917 }
Nadav Bar766fb022018-01-07 12:18:03 +0200918 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
919 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700920 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 // only allow deep buffering for music stream type
922 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200923 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700924 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700926 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
927 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800929 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700930 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200931 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700932 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800933 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200934 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700935 AUDIO_OUTPUT_FLAG_DIRECT);
936 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700937 }
Eric Laurente552edb2014-03-10 17:42:56 -0700938
Nadav Bar766fb022018-01-07 12:18:03 +0200939
Eric Laurentb732cf52014-09-24 19:08:21 -0700940 sp<IOProfile> profile;
941
942 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700943 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200944 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800945 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
946 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700947 goto non_direct_output;
948 }
949
Andy Hung2ddee192015-12-18 17:34:44 -0800950 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
951 // This prevents creating an offloaded track and tearing it down immediately after start
952 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700953 // FIXME: We should check the audio session here but we do not have it in this context.
954 // This may prevent offloading in rare situations where effects are left active by apps
955 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700956
Nadav Bar766fb022018-01-07 12:18:03 +0200957 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800958 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700959 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800960 config->sample_rate,
961 config->format,
962 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200963 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700964 }
965
Eric Laurent1c333e22014-05-20 10:48:17 -0700966 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700967 // exclusive outputs for MMAP and Offload are enforced by different session ids.
968 for (size_t i = 0; i < mOutputs.size(); i++) {
969 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
970 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
971 // reuse direct output if currently open by the same client
972 // and configured with same parameters
973 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700974 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700975 (config->channel_mask == desc->mChannelMask) &&
976 (session == desc->mDirectClientSession)) {
977 desc->mDirectOpenCount++;
978 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
979 mOutputs.keyAt(i), session);
980 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700981 }
982 }
983 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800984
985 if (!profile->canOpenNewIo()) {
986 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
Eric Laurent861a6282015-05-18 15:40:16 -0700988
Eric Laurent3974e3b2017-12-07 17:58:43 -0800989 sp<SwAudioOutputDescriptor> outputDesc =
990 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800991
Mikhail Naganov708e0382018-05-30 09:53:04 -0700992 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800993 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
994 : String8("");
995
Dean Wheatley3023b382018-08-09 07:42:40 +1000996 // MSD patch may be using the only output stream that can service this request. Release
997 // MSD patch to prioritize this request over any active output on MSD.
998 AudioPatchCollection msdPatches = getMsdPatches();
999 for (size_t i = 0; i < msdPatches.size(); i++) {
1000 const auto& patch = msdPatches[i];
1001 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1002 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1003 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1004 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1005 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1006 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1007 releaseAudioPatch(patch->mHandle, mUidCached);
1008 break;
1009 }
1010 }
1011 }
1012
Nadav Bar766fb022018-01-07 12:18:03 +02001013 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001014
1015 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001017 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001018 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001019 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1020 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1021 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1022 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1023 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001024 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001025 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001027 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001028 if (audio_is_linear_pcm(config->format) &&
1029 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 goto non_direct_output;
1031 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001032 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001034 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001035 outputDesc->mDirectClientSession = session;
1036
Eric Laurente552edb2014-03-10 17:42:56 -07001037 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001038 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001039 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001040 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001041 return output;
1042 }
1043
Eric Laurentb732cf52014-09-24 19:08:21 -07001044non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001045
1046 // A request for HW A/V sync cannot fallback to a mixed output because time
1047 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001048 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001049 return AUDIO_IO_HANDLE_NONE;
1050 }
1051
Eric Laurente552edb2014-03-10 17:42:56 -07001052 // ignoring channel mask due to downmix capability in mixer
1053
1054 // open a non direct output
1055
1056 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001057 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001058 // get which output is suitable for the specified stream. The actual
1059 // routing change will happen when startOutput() will be called
1060 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1061
Eric Laurent8838a382014-09-08 16:44:28 -07001062 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001063 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1064 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001065 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001066 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001067 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001068 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001069
Eric Laurente552edb2014-03-10 17:42:56 -07001070 return output;
1071}
1072
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001073sp<HwModule> AudioPolicyManager::getMsdModule() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001074 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001075 if (msdModule != 0 && property_get_bool("audio.msd.disable", false /* default_value */)) {
1076 ALOGI("use of the MSD module is disabled by audio.msd.disable property");
1077 return 0;
1078 }
1079 return msdModule;
1080}
1081
1082sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1083 sp<HwModule> msdModule = getMsdModule();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001084 if (msdModule != 0) {
1085 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1086 msdModule->getHandle());
1087 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1088 }
1089 return 0;
1090}
1091
1092audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001093 sp<HwModule> msdModule = getMsdModule();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001094 if (msdModule != 0) {
1095 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1096 }
1097 return AUDIO_DEVICE_NONE;
1098}
1099
1100const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1101 AudioPatchCollection msdPatches;
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001102 // This function ignores audio.msd.disable property to allow patch teardown.
Mikhail Naganov86112352018-10-04 09:02:49 -07001103 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1104 if (msdModule != 0) {
1105 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1106 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1107 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1108 const struct audio_port_config *source = &patch->mPatch.sources[j];
1109 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1110 source->ext.device.hw_module == msdModule->getHandle()) {
1111 msdPatches.addAudioPatch(patch->mHandle, patch);
1112 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001113 }
1114 }
1115 }
1116 return msdPatches;
1117}
1118
1119status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1120 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1121{
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001122 sp<HwModule> msdModule = getMsdModule();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001123 if (msdModule == nullptr) {
1124 ALOGE("%s() unable to get MSD module", __func__);
1125 return NO_INIT;
1126 }
1127 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1128 if (deviceModule == nullptr) {
1129 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1130 return NO_INIT;
1131 }
1132 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1133 if (inputProfiles.isEmpty()) {
1134 ALOGE("%s() no input profiles for MSD module", __func__);
1135 return NO_INIT;
1136 }
1137 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1138 if (outputProfiles.isEmpty()) {
1139 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1140 return NO_INIT;
1141 }
1142 AudioProfileVector msdProfiles;
1143 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1144 for (const auto &inProfile : inputProfiles) {
1145 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1146 msdProfiles.appendVector(inProfile->getAudioProfiles());
1147 }
1148 }
1149 AudioProfileVector deviceProfiles;
1150 for (const auto &outProfile : outputProfiles) {
1151 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1152 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1153 }
1154 }
1155 struct audio_config_base bestSinkConfig;
1156 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1157 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1158 &bestSinkConfig);
1159 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001160 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1161 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001162 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001163 }
1164 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1165 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1166 sinkConfig->format = bestSinkConfig.format;
1167 // For encoded streams force direct flag to prevent downstream mixing.
1168 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1169 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1170 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1171 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1172 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1173 sourceConfig->format = bestSinkConfig.format;
1174 // Copy input stream directly without any processing (e.g. resampling).
1175 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1176 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1177 if (hwAvSync) {
1178 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1179 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1180 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1181 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1182 }
1183 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1184 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1185 sinkConfig->config_mask |= config_mask;
1186 sourceConfig->config_mask |= config_mask;
1187 return NO_ERROR;
1188}
1189
1190PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1191{
1192 PatchBuilder patchBuilder;
1193 patchBuilder.addSource(getMsdAudioInDevice()).
1194 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1195 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1196 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1197 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1198 // For now, we just forcefully try with HwAvSync first.
1199 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1200 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1201 getBestMsdAudioProfileFor(
1202 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1203 if (res == NO_ERROR) {
1204 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1205 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1206 }
1207 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1208 " supporting PCM format conversion.", __func__);
1209 return patchBuilder;
1210}
1211
1212status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1213 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1214 if (outputDevice == AUDIO_DEVICE_NONE) {
1215 // Use media strategy for unspecified output device. This should only
1216 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1217 // therefore invalidate explicit routing requests.
1218 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1219 }
1220 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1221 const struct audio_patch* patch = patchBuilder.patch();
1222 const AudioPatchCollection msdPatches = getMsdPatches();
1223 if (!msdPatches.isEmpty()) {
1224 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1225 "The current MSD prototype only supports one output patch");
1226 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1227 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1228 return NO_ERROR;
1229 }
1230 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1231 }
1232 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1233 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1234 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1235 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1236 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1237 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1238 return status;
1239}
1240
Eric Laurente0720872014-03-11 09:30:41 -07001241audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001242 audio_output_flags_t flags,
1243 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001244{
1245 // select one output among several that provide a path to a particular device or set of
1246 // devices (the list was previously build by getOutputsForDevice()).
1247 // The priority is as follows:
1248 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001249 // 2: the output with the bit depth the closest to the requested one
1250 // 3: the primary output
1251 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001252
1253 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001254 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001255 }
1256 if (outputs.size() == 1) {
1257 return outputs[0];
1258 }
1259
1260 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001261 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1262 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1263 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001264 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1265 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001266
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001267 for (audio_io_handle_t output : outputs) {
1268 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001269 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001270 // if a valid format is specified, skip output if not compatible
1271 if (format != AUDIO_FORMAT_INVALID) {
1272 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001273 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001274 continue;
1275 }
1276 } else if (!audio_is_linear_pcm(format)) {
1277 continue;
1278 }
Eric Laurente6930022016-02-11 10:20:40 -08001279 if (AudioPort::isBetterFormatMatch(
1280 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001281 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001282 bestFormat = outputDesc->mFormat;
1283 }
Eric Laurent8838a382014-09-08 16:44:28 -07001284 }
1285
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001286 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001287 if (commonFlags >= maxCommonFlags) {
1288 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001289 if (format != AUDIO_FORMAT_INVALID
1290 && AudioPort::isBetterFormatMatch(
1291 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001292 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001293 bestFormatForFlags = outputDesc->mFormat;
1294 }
1295 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001296 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001297 maxCommonFlags = commonFlags;
1298 bestFormatForFlags = outputDesc->mFormat;
1299 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001300 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001301 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001302 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
1305 }
1306 }
1307
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001308 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001309 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001310 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001311 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001312 return outputForFormat;
1313 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001314 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001315 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001316 }
1317
1318 return outputs[0];
1319}
1320
Eric Laurent8fc147b2018-07-22 19:13:55 -07001321status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001322{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001323 ALOGV("%s portId %d", __FUNCTION__, portId);
1324
1325 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1326 if (outputDesc == 0) {
1327 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001328 return BAD_VALUE;
1329 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001330 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001331
Eric Laurent8fc147b2018-07-22 19:13:55 -07001332 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001333 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
Eric Laurent733ce942017-12-07 12:18:25 -08001335 status_t status = outputDesc->start();
1336 if (status != NO_ERROR) {
1337 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001338 }
1339
Eric Laurent97ac8712018-07-27 18:59:02 -07001340 uint32_t delayMs;
1341 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001342
1343 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001344 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001345 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001347 if (delayMs != 0) {
1348 usleep(delayMs * 1000);
1349 }
1350
1351 return status;
1352}
1353
Eric Laurent97ac8712018-07-27 18:59:02 -07001354status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1355 const sp<TrackClientDescriptor>& client,
1356 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001357{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001358 // cannot start playback of STREAM_TTS if any other output is being used
1359 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001360
1361 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001362 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001363 if (stream == AUDIO_STREAM_TTS) {
1364 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001365 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001366 return INVALID_OPERATION;
1367 } else {
1368 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1369 }
1370 } else {
1371 // some playback other than beacon starts
1372 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1373 }
1374
Eric Laurent77305a62016-07-25 16:39:22 -07001375 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001376 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001377 bool force = !outputDesc->isActive() &&
1378 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001379
Eric Laurent97ac8712018-07-27 18:59:02 -07001380 audio_devices_t device = AUDIO_DEVICE_NONE;
1381 AudioMix *policyMix = NULL;
1382 const char *address = NULL;
1383 if (outputDesc->mPolicyMix != NULL) {
1384 policyMix = outputDesc->mPolicyMix;
1385 address = policyMix->mDeviceAddress.string();
1386 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1387 device = policyMix->mDeviceType;
1388 } else {
1389 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1390 }
1391 }
1392
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001393 // requiresMuteCheck is false when we can bypass mute strategy.
1394 // It covers a common case when there is no materially active audio
1395 // and muting would result in unnecessary delay and dropped audio.
1396 const uint32_t outputLatencyMs = outputDesc->latency();
1397 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1398
Eric Laurente552edb2014-03-10 17:42:56 -07001399 // increment usage count for this stream on the requested output:
1400 // NOTE that the usage count is the same for duplicated output and hardware output which is
1401 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001402 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001403
1404 if (client->hasPreferredDevice(true)) {
1405 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1406 if (device != outputDesc->device()) {
1407 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1408 }
1409 }
Eric Laurente552edb2014-03-10 17:42:56 -07001410
Eric Laurent36829f92017-04-07 19:04:42 -07001411 if (stream == AUDIO_STREAM_MUSIC) {
1412 selectOutputForMusicEffects();
1413 }
1414
Eric Laurent592dd7b2018-08-05 18:58:48 -07001415 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001416 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001417 if (device == AUDIO_DEVICE_NONE) {
1418 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001419 }
Eric Laurent36829f92017-04-07 19:04:42 -07001420
Eric Laurente552edb2014-03-10 17:42:56 -07001421 routing_strategy strategy = getStrategy(stream);
1422 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001423 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1424 (beaconMuteLatency > 0);
1425 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001426 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001428 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001429 // An output has a shared device if
1430 // - managed by the same hw module
1431 // - supports the currently selected device
1432 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1433 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1434
Eric Laurent77305a62016-07-25 16:39:22 -07001435 // force a device change if any other output is:
1436 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001437 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001438 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001439 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001440 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001441 // change the device currently selected by the other output.
1442 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001443 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001444 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001445 force = true;
1446 }
1447 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001448 // a notification so that audio focus effect can propagate, or that a mute/unmute
1449 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001450 const uint32_t latencyMs = desc->latency();
1451 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1452
1453 if (shouldWait && isActive && (waitMs < latencyMs)) {
1454 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001456
1457 // Require mute check if another output is on a shared device
1458 // and currently active to have proper drain and avoid pops.
1459 // Note restoring AudioTracks onto this output needs to invoke
1460 // a volume ramp if there is no mute.
1461 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001462 }
1463 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001464
1465 const uint32_t muteWaitMs =
1466 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001467
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // apply volume rules for current stream and device if necessary
1469 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001470 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001471 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001472 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001473
1474 // update the outputs if starting an output with a stream that can affect notification
1475 // routing
1476 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001477
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001478 // force reevaluating accessibility routing when ringtone or alarm starts
1479 if (strategy == STRATEGY_SONIFICATION) {
1480 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1481 }
Eric Laurentdc462862016-07-19 12:29:53 -07001482
1483 if (waitMs > muteWaitMs) {
1484 *delayMs = waitMs - muteWaitMs;
1485 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001486
1487 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1488 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1489 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1490 // change occurs after the MixerThread starts and causes a stream volume
1491 // glitch.
1492 //
1493 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001494 }
Eric Laurentdc462862016-07-19 12:29:53 -07001495
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001496 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1497 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1498 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1499 }
1500
Eric Laurent97ac8712018-07-27 18:59:02 -07001501 // Automatically enable the remote submix input when output is started on a re routing mix
1502 // of type MIX_TYPE_RECORDERS
1503 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1504 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1505 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1507 address,
1508 "remote-submix");
1509 }
1510
Eric Laurente552edb2014-03-10 17:42:56 -07001511 return NO_ERROR;
1512}
1513
Eric Laurent8fc147b2018-07-22 19:13:55 -07001514status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001515{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001516 ALOGV("%s portId %d", __FUNCTION__, portId);
1517
1518 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1519 if (outputDesc == 0) {
1520 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 return BAD_VALUE;
1522 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001523 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001524
Eric Laurent97ac8712018-07-27 18:59:02 -07001525 ALOGV("stopOutput() output %d, stream %d, session %d",
1526 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001527
Eric Laurent97ac8712018-07-27 18:59:02 -07001528 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001529
Eric Laurent733ce942017-12-07 12:18:25 -08001530 if (status == NO_ERROR ) {
1531 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001532 }
1533 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001534}
1535
Eric Laurent97ac8712018-07-27 18:59:02 -07001536status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1537 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001538{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001539 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001540 audio_stream_type_t stream = client->stream();
1541
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001542 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1543
Eric Laurent592dd7b2018-08-05 18:58:48 -07001544 if (outputDesc->streamActiveCount(stream) > 0) {
1545 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001546 // Automatically disable the remote submix input when output is stopped on a
1547 // re routing mix of type MIX_TYPE_RECORDERS
1548 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1549 outputDesc->mPolicyMix != NULL &&
1550 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1551 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1552 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1553 outputDesc->mPolicyMix->mDeviceAddress,
1554 "remote-submix");
1555 }
1556 }
1557 bool forceDeviceUpdate = false;
1558 if (client->hasPreferredDevice(true)) {
1559 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1560 forceDeviceUpdate = true;
1561 }
1562
Eric Laurente552edb2014-03-10 17:42:56 -07001563 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001564 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001565
Eric Laurente552edb2014-03-10 17:42:56 -07001566 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001567 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001568 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001569 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001570 // delay the device switch by twice the latency because stopOutput() is executed when
1571 // the track stop() command is received and at that time the audio track buffer can
1572 // still contain data that needs to be drained. The latency only covers the audio HAL
1573 // and kernel buffers. Also the latency does not always include additional delay in the
1574 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001576
1577 // force restoring the device selection on other active outputs if it differs from the
1578 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001579 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001580 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001581 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001582 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001583 desc->isActive() &&
1584 outputDesc->sharesHwModuleWith(desc) &&
1585 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001586 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1587 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001588
Eric Laurentc75307b2015-03-17 15:29:32 -07001589 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001590 newDevice2,
1591 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001592 delayMs);
1593 // re-apply device specific volume if not done by setOutputDevice()
1594 if (!force) {
1595 applyStreamVolumes(desc, newDevice2, delayMs);
1596 }
Eric Laurente552edb2014-03-10 17:42:56 -07001597 }
1598 }
1599 // update the outputs if stopping one with a stream that can affect notification routing
1600 handleNotificationRoutingForStream(stream);
1601 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001602
1603 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1604 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1605 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1606 }
1607
Eric Laurent36829f92017-04-07 19:04:42 -07001608 if (stream == AUDIO_STREAM_MUSIC) {
1609 selectOutputForMusicEffects();
1610 }
Eric Laurente552edb2014-03-10 17:42:56 -07001611 return NO_ERROR;
1612 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001613 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001614 return INVALID_OPERATION;
1615 }
1616}
1617
Eric Laurent8fc147b2018-07-22 19:13:55 -07001618void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001619{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001620 ALOGV("%s portId %d", __FUNCTION__, portId);
1621
1622 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1623 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001624 // If an output descriptor is closed due to a device routing change,
1625 // then there are race conditions with releaseOutput from tracks
1626 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1627 // destroyed shortly thereafter.
1628 //
1629 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001631 return;
1632 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001633
1634 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001635
Eric Laurent8fc147b2018-07-22 19:13:55 -07001636 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1637 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001638 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001639 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001640 return;
1641 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001642 if (--outputDesc->mDirectOpenCount == 0) {
1643 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001644 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001645 }
1646 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001647 // stopOutput() needs to be successfully called before releaseOutput()
1648 // otherwise there may be inaccurate stream reference counts.
1649 // This is checked in outputDesc->removeClient below.
1650 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001651}
1652
Eric Laurentcaf7f482014-11-25 17:50:47 -08001653status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1654 audio_io_handle_t *input,
1655 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001656 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001657 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001658 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001659 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001660 input_type_t *inputType,
1661 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001662{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001663 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001664 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001665 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001666
Eric Laurentad2e7b92017-09-14 20:06:42 -07001667 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001668 // handle legacy remote submix case where the address was not always specified
1669 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001670 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001671 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001672 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001673 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001674 sp<AudioInputDescriptor> inputDesc;
1675 sp<RecordClientDescriptor> clientDesc;
1676 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001677 bool isSoundTrigger;
1678 audio_devices_t device;
1679
1680 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1681 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1682 return INVALID_OPERATION;
1683 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001684
Eric Laurentfe231122017-11-17 17:48:06 -08001685 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1686 inputSource = AUDIO_SOURCE_MIC;
1687 }
1688
Paul McLean466dc8e2015-04-17 13:15:36 -06001689 // Explicit routing?
1690 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001691 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001692 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001693 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001694
Eric Laurentad2e7b92017-09-14 20:06:42 -07001695 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1696 // possible
1697 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1698 *input != AUDIO_IO_HANDLE_NONE) {
1699 ssize_t index = mInputs.indexOfKey(*input);
1700 if (index < 0) {
1701 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1702 status = BAD_VALUE;
1703 goto error;
1704 }
1705 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001706 RecordClientVector clients = inputDesc->getClientsForSession(session);
1707 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001708 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1709 status = BAD_VALUE;
1710 goto error;
1711 }
1712 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1713 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001714 // corresponds to a new client and is only permitted from the same UID.
1715 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001716 if (clients.size() > 1) {
1717 for (const auto& client : clients) {
1718 // The client map is ordered by key values (portId) and portIds are allocated
1719 // incrementaly. So the first client in this list is the one opened by audio flinger
1720 // when the mmap stream is created and should be ignored as it does not correspond
1721 // to an actual client
1722 if (client == *clients.cbegin()) {
1723 continue;
1724 }
1725 if (uid != client->uid() && !client->isSilenced()) {
1726 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1727 uid, client->portId(), client->uid());
1728 status = INVALID_OPERATION;
1729 goto error;
1730 }
Eric Laurent331679c2018-04-16 17:03:16 -07001731 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001732 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001734 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735
Eric Laurent8f42ea12018-08-08 09:08:25 -07001736 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001737 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001738 }
1739
1740 *input = AUDIO_IO_HANDLE_NONE;
1741 *inputType = API_INPUT_INVALID;
1742
Eric Laurentad2e7b92017-09-14 20:06:42 -07001743 halInputSource = inputSource;
1744
Eric Laurentc447ded2015-01-06 08:47:05 -08001745 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1748 if (status != NO_ERROR) {
1749 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001750 }
1751 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001752 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1753 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001754 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001755 if (deviceDesc != 0) {
1756 device = deviceDesc->type();
1757 } else {
1758 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1759 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001760 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001761 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001762 status = BAD_VALUE;
1763 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001764 }
Eric Laurentc722f302014-12-10 11:21:49 -08001765 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001766 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001767 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1768 // there is an external policy, but this input is attached to a mix of recorders,
1769 // meaning it receives audio injected into the framework, so the recorder doesn't
1770 // know about it and is therefore considered "legacy"
1771 *inputType = API_INPUT_LEGACY;
1772 } else {
1773 // recording a mix of players defined by an external policy, we're rerouting for
1774 // an external policy
1775 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1776 }
Eric Laurentc722f302014-12-10 11:21:49 -08001777 } else if (audio_is_remote_submix_device(device)) {
1778 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001779 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001780 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1781 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001782 } else {
1783 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001784 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001785
Eric Laurent599c7582015-12-07 18:05:55 -08001786 }
1787
Eric Laurent8f42ea12018-08-08 09:08:25 -07001788 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001789 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001790 policyMix);
1791 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001792 status = INVALID_OPERATION;
1793 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001794 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001795
Eric Laurent8f42ea12018-08-08 09:08:25 -07001796exit:
1797
Mikhail Naganov708e0382018-05-30 09:53:04 -07001798 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001799 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001800 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001801
Eric Laurent8f42ea12018-08-08 09:08:25 -07001802 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1803 mSoundTriggerSessions.indexOfKey(session) > 0;
1804 *portId = AudioPort::getNextUniqueId();
1805
Eric Laurent8fc147b2018-07-22 19:13:55 -07001806 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001807 *attr, *config, requestedDeviceId,
1808 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001809 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001810 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001811
1812 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1813 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001814
Eric Laurent599c7582015-12-07 18:05:55 -08001815 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001816
1817error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001818 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001819}
1820
1821
1822audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1823 String8 address,
1824 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001825 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001826 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001827 audio_input_flags_t flags,
1828 AudioMix *policyMix)
1829{
1830 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1831 audio_source_t halInputSource = inputSource;
1832 bool isSoundTrigger = false;
1833
1834 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1835 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1836 if (index >= 0) {
1837 input = mSoundTriggerSessions.valueFor(session);
1838 isSoundTrigger = true;
1839 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1840 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1841 } else {
1842 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001843 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001844 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001845 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001846 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001847 }
1848
Andy Hungf129b032015-04-07 13:45:50 -07001849 // find a compatible input profile (not necessarily identical in parameters)
1850 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001851 // sampling rate and flags may be updated by getInputProfile
1852 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1853 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001854 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001855 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001856 audio_input_flags_t profileFlags = flags;
1857 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001858 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001859 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001860 profileSamplingRate, profileFormat, profileChannelMask,
1861 profileFlags);
1862 if (profile != 0) {
1863 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001864 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1865 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001866 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1867 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1868 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001869 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001870 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1871 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001872 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001873 }
Eric Laurente552edb2014-03-10 17:42:56 -07001874 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001875 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001876 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001877 if (samplingRate == 0) {
1878 samplingRate = profileSamplingRate;
1879 }
Eric Laurente552edb2014-03-10 17:42:56 -07001880
Eric Laurent322b4d22015-04-03 15:57:54 -07001881 if (profile->getModuleHandle() == 0) {
1882 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001883 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001884 }
1885
Eric Laurent3974e3b2017-12-07 17:58:43 -08001886 if (!profile->canOpenNewIo()) {
1887 return AUDIO_IO_HANDLE_NONE;
1888 }
1889
Eric Laurentfe231122017-11-17 17:48:06 -08001890 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001891
Eric Laurentfe231122017-11-17 17:48:06 -08001892 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1893 lConfig.sample_rate = profileSamplingRate;
1894 lConfig.channel_mask = profileChannelMask;
1895 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001896
Eric Laurent53b810e2017-12-10 17:25:10 -08001897 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001898 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001899 // the inputs vector must be of size >= 1, but we don't want to crash here
1900 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1901 }
1902
Eric Laurentfe231122017-11-17 17:48:06 -08001903 status_t status = inputDesc->open(&lConfig, device, address,
1904 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001905
1906 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001907 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001908 (profileSamplingRate != lConfig.sample_rate) ||
1909 !audio_formats_match(profileFormat, lConfig.format) ||
1910 (profileChannelMask != lConfig.channel_mask)) {
1911 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001912 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001913 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001914 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001915 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001916 }
Eric Laurent599c7582015-12-07 18:05:55 -08001917 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001918 }
1919
Eric Laurentc722f302014-12-10 11:21:49 -08001920 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001921
Eric Laurent599c7582015-12-07 18:05:55 -08001922 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001923 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001924
Eric Laurent599c7582015-12-07 18:05:55 -08001925 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001926}
1927
Eric Laurentbb948092017-01-23 18:33:30 -08001928//static
1929bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1930{
1931 return (source == AUDIO_SOURCE_HOTWORD) ||
1932 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1933 (source == AUDIO_SOURCE_FM_TUNER);
1934}
1935
Chris Thornton2b864642017-06-27 21:26:07 -07001936// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1937bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1938 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1939 bool soundTriggerSupportsConcurrentCapture = false;
1940 unsigned int numModules = 0;
1941 struct sound_trigger_module_descriptor* nModules = NULL;
1942
1943 status_t status = SoundTrigger::listModules(nModules, &numModules);
1944 if (status == NO_ERROR && numModules != 0) {
1945 nModules = (struct sound_trigger_module_descriptor*) calloc(
1946 numModules, sizeof(struct sound_trigger_module_descriptor));
1947 if (nModules == NULL) {
1948 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1949 // ram the next time this function is called.
1950 ALOGE("Failed to allocate buffer for module descriptors");
1951 return false;
1952 }
1953
1954 status = SoundTrigger::listModules(nModules, &numModules);
1955 if (status == NO_ERROR) {
1956 soundTriggerSupportsConcurrentCapture = true;
1957 for (size_t i = 0; i < numModules; ++i) {
1958 soundTriggerSupportsConcurrentCapture &=
1959 nModules[i].properties.concurrent_capture;
1960 }
1961 }
1962 free(nModules);
1963 }
1964 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1965 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1966 }
1967 return mSoundTriggerSupportsConcurrentCapture;
1968}
1969
Eric Laurentfb66dd92016-01-28 18:32:03 -08001970
Eric Laurent8fc147b2018-07-22 19:13:55 -07001971status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001972 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001973 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001974{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001975 *concurrency = API_INPUT_CONCURRENCY_NONE;
1976
1977 ALOGV("%s portId %d", __FUNCTION__, portId);
1978
1979 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1980 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001981 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001982 return BAD_VALUE;
1983 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001984 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001985 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001986 if (client->active()) {
1987 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1988 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001989 }
1990
Eric Laurent8f42ea12018-08-08 09:08:25 -07001991 audio_session_t session = client->session();
1992
1993 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1994 __FUNCTION__, input, session, silenced, *concurrency);
1995
Eric Laurent74708e72017-04-07 17:13:42 -07001996 if (!is_virtual_input_device(inputDesc->mDevice)) {
1997 if (mCallTxPatch != 0 &&
1998 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1999 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07002000 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07002001 return INVALID_OPERATION;
2002 }
2003
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002004 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002005
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002006 // If a UID is idle and records silence and another not silenced recording starts
2007 // from another UID (idle or active) we stop the current idle UID recording in
2008 // favor of the new one - "There can be only one" TM
2009 if (!silenced) {
2010 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002011 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002012 activeDesc->getId() == inputDesc->getId()) {
2013 continue;
2014 }
2015
Eric Laurent8f42ea12018-08-08 09:08:25 -07002016 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2017 for (const auto& activeClient : activeClients) {
2018 if (activeClient->isSilenced()) {
2019 closeClient(activeClient->portId());
2020 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2021 portId, activeClient->portId());
2022 activeInputs = mInputs.getActiveInputs();
2023 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002024 }
2025 }
2026 }
2027
2028 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002029 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002030 activeDesc->getId() == inputDesc->getId()) {
2031 continue;
2032 }
2033
Eric Laurent74708e72017-04-07 17:13:42 -07002034 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002036 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2037 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 ALOGW("%s input %d failed for HOTWORD: "
2039 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002040 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002041 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002042 return INVALID_OPERATION;
2043 }
2044 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002045 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2046 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002047 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002048 return INVALID_OPERATION;
2049 }
2050 } else {
2051 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002052 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002053 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002054 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002055 return INVALID_OPERATION;
2056 }
2057 }
2058 }
2059
Chris Thornton2b864642017-06-27 21:26:07 -07002060 // We only need to check if the sound trigger session supports concurrent capture if the
2061 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2062 // that's running.
2063 const bool allowConcurrentWithSoundTrigger =
2064 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2065
Eric Laurent74708e72017-04-07 17:13:42 -07002066 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002067 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002068 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2069 continue;
2070 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 RecordClientVector activeHotwordClients =
2072 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2073 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002074 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002075
2076 for (const auto& activeClient : activeHotwordClients) {
2077 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2078 sessions.add(activeClient->session());
2079 closeClient(activeClient->portId());
2080 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2081 input, activeDesc->mIoHandle);
2082 }
2083
Eric Laurent74708e72017-04-07 17:13:42 -07002084 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002085 }
2086 }
2087 }
Eric Laurente552edb2014-03-10 17:42:56 -07002088
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002089 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002090 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002091
Eric Laurent313d1e72016-01-29 09:56:57 -08002092 // increment activity count before calling getNewInputDevice() below as only active sessions
2093 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002094 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002095
Eric Laurent8f42ea12018-08-08 09:08:25 -07002096 // indicate active capture to sound trigger service if starting capture from a mic on
2097 // primary HW module
2098 audio_devices_t device = getNewInputDevice(inputDesc);
2099 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002100
Eric Laurent8f42ea12018-08-08 09:08:25 -07002101 status_t status = inputDesc->start();
2102 if (status != NO_ERROR) {
2103 inputDesc->setClientActive(client, false);
2104 return status;
2105 }
2106
2107 if (inputDesc->activeCount() == 1) {
2108 // if input maps to a dynamic policy with an activity listener, notify of state change
2109 if ((inputDesc->mPolicyMix != NULL)
2110 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2111 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2112 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002113 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002114
Eric Laurent8f42ea12018-08-08 09:08:25 -07002115 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2116 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2117 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2118 SoundTrigger::setCaptureState(true);
2119 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002120
Eric Laurent8f42ea12018-08-08 09:08:25 -07002121 // automatically enable the remote submix output when input is started if not
2122 // used by a policy mix of type MIX_TYPE_RECORDERS
2123 // For remote submix (a virtual device), we open only one input per capture request.
2124 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2125 String8 address = String8("");
2126 if (inputDesc->mPolicyMix == NULL) {
2127 address = String8("0");
2128 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2129 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002130 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 if (address != "") {
2132 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2133 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2134 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002135 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002136 }
Eric Laurente552edb2014-03-10 17:42:56 -07002137 }
2138
Eric Laurent8f42ea12018-08-08 09:08:25 -07002139 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002140
Eric Laurente552edb2014-03-10 17:42:56 -07002141 return NO_ERROR;
2142}
2143
Eric Laurent8fc147b2018-07-22 19:13:55 -07002144status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002145{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002146 ALOGV("%s portId %d", __FUNCTION__, portId);
2147
2148 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2149 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002150 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002151 return BAD_VALUE;
2152 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002153 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002154 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002155 if (!client->active()) {
2156 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002157 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002158 }
2159
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002161
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162 inputDesc->stop();
2163 if (inputDesc->isActive()) {
2164 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2165 } else {
2166 // if input maps to a dynamic policy with an activity listener, notify of state change
2167 if ((inputDesc->mPolicyMix != NULL)
2168 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2169 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2170 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002171 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002172
2173 // automatically disable the remote submix output when input is stopped if not
2174 // used by a policy mix of type MIX_TYPE_RECORDERS
2175 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2176 String8 address = String8("");
2177 if (inputDesc->mPolicyMix == NULL) {
2178 address = String8("0");
2179 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2180 address = inputDesc->mPolicyMix->mDeviceAddress;
2181 }
2182 if (address != "") {
2183 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2184 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2185 address, "remote-submix");
2186 }
2187 }
2188
2189 audio_devices_t device = inputDesc->mDevice;
2190 resetInputDevice(input);
2191
2192 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2193 // primary HW module
2194 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2195 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2196 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2197 SoundTrigger::setCaptureState(false);
2198 }
2199 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002200 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002201 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002202}
2203
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002205{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002206 ALOGV("%s portId %d", __FUNCTION__, portId);
2207
2208 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2209 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002211 return;
2212 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002213 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002214 audio_io_handle_t input = inputDesc->mIoHandle;
2215
Eric Laurent8f42ea12018-08-08 09:08:25 -07002216 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002217
Andy Hung39efb7a2018-09-26 15:39:28 -07002218 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002219
Andy Hung39efb7a2018-09-26 15:39:28 -07002220 if (inputDesc->getClientCount() > 0) {
2221 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002222 return;
2223 }
2224
Eric Laurent05b90f82014-08-27 15:32:29 -07002225 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002226 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002227 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002228}
2229
Eric Laurent8f42ea12018-08-08 09:08:25 -07002230void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002231{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002232 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002233
2234 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002235 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236 }
2237}
2238
Eric Laurent8f42ea12018-08-08 09:08:25 -07002239void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2240{
2241 stopInput(portId);
2242 releaseInput(portId);
2243}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002244
Eric Laurentd4692962014-05-05 18:13:44 -07002245void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002246 bool patchRemoved = false;
2247
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002248 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002249 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002250 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002251 if (patch_index >= 0) {
2252 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002253 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002254 mAudioPatches.removeItemsAt(patch_index);
2255 patchRemoved = true;
2256 }
Eric Laurentfe231122017-11-17 17:48:06 -08002257 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002258 }
2259 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002260 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002261 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002262
2263 if (patchRemoved) {
2264 mpClientInterface->onAudioPatchListUpdate();
2265 }
Eric Laurentd4692962014-05-05 18:13:44 -07002266}
2267
Eric Laurente0720872014-03-11 09:30:41 -07002268void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002269 int indexMin,
2270 int indexMax)
2271{
2272 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002273 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002274
2275 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002276 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2277 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 continue;
2279 }
2280 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282}
2283
Eric Laurente0720872014-03-11 09:30:41 -07002284status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002285 int index,
2286 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002287{
2288
Nadav Bar7c605f62017-12-25 00:01:52 +02002289 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2290 // app that has MODIFY_PHONE_STATE permission.
2291 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2292 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002293 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002294 return BAD_VALUE;
2295 }
2296 if (!audio_is_output_device(device)) {
2297 return BAD_VALUE;
2298 }
2299
2300 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002301 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002302
Eric Laurent1fd372e2016-04-06 14:23:53 -07002303 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002304 stream, device, index);
2305
Eric Laurent28d09f02016-03-08 10:43:05 -08002306 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002307 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2308 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002309 continue;
2310 }
2311 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2312 }
Eric Laurente552edb2014-03-10 17:42:56 -07002313
Eric Laurent1fd372e2016-04-06 14:23:53 -07002314 // update volume on all outputs and streams matching the following:
2315 // - The requested stream (or a stream matching for volume control) is active on the output
2316 // - The device (or devices) selected by the strategy corresponding to this stream includes
2317 // the requested device
2318 // - For non default requested device, currently selected device on the output is either the
2319 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002320 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2321 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002322 status_t status = NO_ERROR;
2323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2325 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002326 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002327 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002328 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002329 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002330 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002331 continue;
2332 }
Eric Laurent794fde22016-03-11 09:50:45 -08002333 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002334 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2335 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002336 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2337 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002338 continue;
2339 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002340 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002341 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002342 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002343 applyVolume = (curDevice & curStreamDevice) != 0;
2344 } else {
2345 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002346 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002347 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002348 // rescale index before applying to curStream as ranges may be different for
2349 // stream and curStream
2350 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002351 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002352 //FIXME: workaround for truncated touch sounds
2353 // delayed volume change for system stream to be removed when the problem is
2354 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002355 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002356 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002357 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002358 if (volStatus != NO_ERROR) {
2359 status = volStatus;
2360 }
2361 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002362 }
Eric Laurente552edb2014-03-10 17:42:56 -07002363 }
2364 return status;
2365}
2366
Eric Laurente0720872014-03-11 09:30:41 -07002367status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002368 int *index,
2369 audio_devices_t device)
2370{
2371 if (index == NULL) {
2372 return BAD_VALUE;
2373 }
2374 if (!audio_is_output_device(device)) {
2375 return BAD_VALUE;
2376 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002377 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002378 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002379 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002380 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2381 }
François Gaffiedfd74092015-03-19 12:10:59 +01002382 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002383
François Gaffied1ab2bd2015-12-02 18:20:06 +01002384 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002385 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2386 return NO_ERROR;
2387}
2388
Eric Laurent36829f92017-04-07 19:04:42 -07002389audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002390{
2391 // select one output among several suitable for global effects.
2392 // The priority is as follows:
2393 // 1: An offloaded output. If the effect ends up not being offloadable,
2394 // AudioFlinger will invalidate the track and the offloaded output
2395 // will be closed causing the effect to be moved to a PCM output.
2396 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002397 // 3: The primary output
2398 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002399
Eric Laurent3b73df72014-03-11 09:06:29 -07002400 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002401 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002402 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002403
Eric Laurent36829f92017-04-07 19:04:42 -07002404 if (outputs.size() == 0) {
2405 return AUDIO_IO_HANDLE_NONE;
2406 }
Eric Laurente552edb2014-03-10 17:42:56 -07002407
Eric Laurent36829f92017-04-07 19:04:42 -07002408 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2409 bool activeOnly = true;
2410
2411 while (output == AUDIO_IO_HANDLE_NONE) {
2412 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2413 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2414 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2415
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002416 for (audio_io_handle_t output : outputs) {
2417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002418 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2419 continue;
2420 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002421 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2422 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002423 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002424 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002425 }
2426 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002427 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002428 }
2429 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002430 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002431 }
2432 }
2433 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2434 output = outputOffloaded;
2435 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2436 output = outputDeepBuffer;
2437 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2438 output = outputPrimary;
2439 } else {
2440 output = outputs[0];
2441 }
2442 activeOnly = false;
2443 }
2444
2445 if (output != mMusicEffectOutput) {
2446 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2447 mMusicEffectOutput = output;
2448 }
2449
2450 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002451 return output;
2452}
2453
Eric Laurent36829f92017-04-07 19:04:42 -07002454audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2455{
2456 return selectOutputForMusicEffects();
2457}
2458
Eric Laurente0720872014-03-11 09:30:41 -07002459status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002460 audio_io_handle_t io,
2461 uint32_t strategy,
2462 int session,
2463 int id)
2464{
2465 ssize_t index = mOutputs.indexOfKey(io);
2466 if (index < 0) {
2467 index = mInputs.indexOfKey(io);
2468 if (index < 0) {
2469 ALOGW("registerEffect() unknown io %d", io);
2470 return INVALID_OPERATION;
2471 }
2472 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002473 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002474}
2475
Eric Laurentc75307b2015-03-17 15:29:32 -07002476bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2477{
Eric Laurent28d09f02016-03-08 10:43:05 -08002478 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002479 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2480 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002481 continue;
2482 }
2483 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2484 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002485 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002486}
2487
2488bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2489{
2490 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2491}
2492
Eric Laurente0720872014-03-11 09:30:41 -07002493bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002494{
2495 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002496 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002497 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002498 return true;
2499 }
2500 }
2501 return false;
2502}
2503
Eric Laurent275e8e92014-11-30 15:14:47 -08002504// Register a list of custom mixes with their attributes and format.
2505// When a mix is registered, corresponding input and output profiles are
2506// added to the remote submix hw module. The profile contains only the
2507// parameters (sampling rate, format...) specified by the mix.
2508// The corresponding input remote submix device is also connected.
2509//
2510// When a remote submix device is connected, the address is checked to select the
2511// appropriate profile and the corresponding input or output stream is opened.
2512//
2513// When capture starts, getInputForAttr() will:
2514// - 1 look for a mix matching the address passed in attribtutes tags if any
2515// - 2 if none found, getDeviceForInputSource() will:
2516// - 2.1 look for a mix matching the attributes source
2517// - 2.2 if none found, default to device selection by policy rules
2518// At this time, the corresponding output remote submix device is also connected
2519// and active playback use cases can be transferred to this mix if needed when reconnecting
2520// after AudioTracks are invalidated
2521//
2522// When playback starts, getOutputForAttr() will:
2523// - 1 look for a mix matching the address passed in attribtutes tags if any
2524// - 2 if none found, look for a mix matching the attributes usage
2525// - 3 if none found, default to device and output selection by policy rules.
2526
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002527status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002528{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2530 status_t res = NO_ERROR;
2531
2532 sp<HwModule> rSubmixModule;
2533 // examine each mix's route type
2534 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002535 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002537 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002538 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002539 break;
2540 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002541 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002542 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002543 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002544 rSubmixModule = mHwModules.getModuleFromName(
2545 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2546 if (rSubmixModule == 0) {
2547 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2548 i);
2549 res = INVALID_OPERATION;
2550 break;
2551 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 String8 address = mix.mDeviceAddress;
2555 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2556 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2557 } else {
2558 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2559 }
François Gaffie036e1e92015-03-19 10:16:24 +01002560
Eric Laurent97ac8712018-07-27 18:59:02 -07002561 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002562 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002563 res = INVALID_OPERATION;
2564 break;
2565 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002566 audio_config_t outputConfig = mix.mFormat;
2567 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2569 // stereo and let audio flinger do the channel conversion if needed.
2570 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2571 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2572 rSubmixModule->addOutputProfile(address, &outputConfig,
2573 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2574 rSubmixModule->addInputProfile(address, &inputConfig,
2575 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002576
Eric Laurent97ac8712018-07-27 18:59:02 -07002577 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2579 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2580 address.string(), "remote-submix");
2581 } else {
2582 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2584 address.string(), "remote-submix");
2585 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2587 String8 address = mix.mDeviceAddress;
2588 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002589 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2590 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002592 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002593 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2594 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2595 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2596 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2597 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2598 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002599 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2600 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002602 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002603 } else {
2604 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002605 }
2606 break;
2607 }
2608 }
2609
2610 if (res != NO_ERROR) {
2611 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002612 i, device, address.string());
2613 res = INVALID_OPERATION;
2614 break;
2615 } else if (!foundOutput) {
2616 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2617 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002618 res = INVALID_OPERATION;
2619 break;
2620 }
Eric Laurentc722f302014-12-10 11:21:49 -08002621 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002622 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002623 if (res != NO_ERROR) {
2624 unregisterPolicyMixes(mixes);
2625 }
2626 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002627}
2628
2629status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2630{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002631 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 status_t res = NO_ERROR;
2633 sp<HwModule> rSubmixModule;
2634 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002635 for (const auto& mix : mixes) {
2636 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002637
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002639 rSubmixModule = mHwModules.getModuleFromName(
2640 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2641 if (rSubmixModule == 0) {
2642 res = INVALID_OPERATION;
2643 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002644 }
2645 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002646
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002647 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002648
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002649 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2650 res = INVALID_OPERATION;
2651 continue;
2652 }
2653
2654 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2655 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2656 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2657 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2658 address.string(), "remote-submix");
2659 }
2660 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2661 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2662 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2663 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2664 address.string(), "remote-submix");
2665 }
2666 rSubmixModule->removeOutputProfile(address);
2667 rSubmixModule->removeInputProfile(address);
2668
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002669 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2670 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002671 res = INVALID_OPERATION;
2672 continue;
2673 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002674 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002675 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002676 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002677}
2678
Andy Hungc29d82b2018-10-05 12:23:17 -07002679void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002680{
Andy Hungc29d82b2018-10-05 12:23:17 -07002681 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2682 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002683 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002684 std::string stateLiteral;
2685 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002686 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002687 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2688 "communications", "media", "record", "dock", "system",
2689 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2690 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2691 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002692 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002693 forceUses[i], mEngine->getForceUse(i));
2694 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002695 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2696 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2697 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2698 mAvailableOutputDevices.dump(dst, String8("Available output"));
2699 mAvailableInputDevices.dump(dst, String8("Available input"));
2700 mHwModulesAll.dump(dst);
2701 mOutputs.dump(dst);
2702 mInputs.dump(dst);
2703 mVolumeCurves->dump(dst);
2704 mEffects.dump(dst);
2705 mAudioPatches.dump(dst);
2706 mPolicyMixes.dump(dst);
2707 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002708 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002709 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002710 size_t i = 0;
2711 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002712 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002713 std::string sfmt;
2714 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002715 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002716 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002717 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002718 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002719}
2720
2721status_t AudioPolicyManager::dump(int fd)
2722{
2723 String8 result;
2724 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002725 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002726 return NO_ERROR;
2727}
2728
2729// This function checks for the parameters which can be offloaded.
2730// This can be enhanced depending on the capability of the DSP and policy
2731// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002732bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002733{
2734 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002735 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002736 offloadInfo.sample_rate, offloadInfo.channel_mask,
2737 offloadInfo.format,
2738 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2739 offloadInfo.has_video);
2740
Andy Hung2ddee192015-12-18 17:34:44 -08002741 if (mMasterMono) {
2742 return false; // no offloading if mono is set.
2743 }
2744
Eric Laurente552edb2014-03-10 17:42:56 -07002745 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002746 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2747 ALOGV("offload disabled by audio.offload.disable");
2748 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002749 }
2750
2751 // Check if stream type is music, then only allow offload as of now.
2752 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2753 {
2754 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2755 return false;
2756 }
2757
2758 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002759 const bool allowOffloadWithVideo =
2760 property_get_bool("audio.offload.video", false /* default_value */);
2761 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002762 ALOGV("isOffloadSupported: has_video == true, returning false");
2763 return false;
2764 }
2765
2766 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002767 const int min_duration_secs = property_get_int32(
2768 "audio.offload.min.duration.secs", -1 /* default_value */);
2769 if (min_duration_secs >= 0) {
2770 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2771 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2772 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002773 return false;
2774 }
2775 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2776 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2777 return false;
2778 }
2779
2780 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2781 // creating an offloaded track and tearing it down immediately after start when audioflinger
2782 // detects there is an active non offloadable effect.
2783 // FIXME: We should check the audio session here but we do not have it in this context.
2784 // This may prevent offloading in rare situations where effects are left active by apps
2785 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002786 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002787 return false;
2788 }
2789
2790 // See if there is a profile to support this.
2791 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002792 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002793 offloadInfo.sample_rate,
2794 offloadInfo.format,
2795 offloadInfo.channel_mask,
2796 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002797 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2798 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002799}
2800
Eric Laurent6a94d692014-05-20 11:18:06 -07002801status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2802 audio_port_type_t type,
2803 unsigned int *num_ports,
2804 struct audio_port *ports,
2805 unsigned int *generation)
2806{
2807 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2808 generation == NULL) {
2809 return BAD_VALUE;
2810 }
2811 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2812 if (ports == NULL) {
2813 *num_ports = 0;
2814 }
2815
2816 size_t portsWritten = 0;
2817 size_t portsMax = *num_ports;
2818 *num_ports = 0;
2819 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002820 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2821 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002823 for (const auto& dev : mAvailableOutputDevices) {
2824 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002825 continue;
2826 }
2827 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002828 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002829 }
2830 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 }
2833 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002834 for (const auto& dev : mAvailableInputDevices) {
2835 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002836 continue;
2837 }
2838 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002839 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002840 }
2841 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002842 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 }
2844 }
2845 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2846 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2847 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2848 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2849 }
2850 *num_ports += mInputs.size();
2851 }
2852 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002853 size_t numOutputs = 0;
2854 for (size_t i = 0; i < mOutputs.size(); i++) {
2855 if (!mOutputs[i]->isDuplicated()) {
2856 numOutputs++;
2857 if (portsWritten < portsMax) {
2858 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2859 }
2860 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002861 }
Eric Laurent84c70242014-06-23 08:46:27 -07002862 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 }
2864 }
2865 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002866 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002867 return NO_ERROR;
2868}
2869
Eric Laurent99fcae42018-05-17 16:59:18 -07002870status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002871{
Eric Laurent99fcae42018-05-17 16:59:18 -07002872 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2873 return BAD_VALUE;
2874 }
2875 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2876 if (dev != 0) {
2877 dev->toAudioPort(port);
2878 return NO_ERROR;
2879 }
2880 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2881 if (dev != 0) {
2882 dev->toAudioPort(port);
2883 return NO_ERROR;
2884 }
2885 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2886 if (out != 0) {
2887 out->toAudioPort(port);
2888 return NO_ERROR;
2889 }
2890 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2891 if (in != 0) {
2892 in->toAudioPort(port);
2893 return NO_ERROR;
2894 }
2895 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002896}
2897
Eric Laurent6a94d692014-05-20 11:18:06 -07002898status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2899 audio_patch_handle_t *handle,
2900 uid_t uid)
2901{
2902 ALOGV("createAudioPatch()");
2903
2904 if (handle == NULL || patch == NULL) {
2905 return BAD_VALUE;
2906 }
2907 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2908
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002909 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002910 return BAD_VALUE;
2911 }
2912 // only one source per audio patch supported for now
2913 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 return INVALID_OPERATION;
2915 }
Eric Laurent874c42872014-08-08 15:13:39 -07002916
2917 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002918 return INVALID_OPERATION;
2919 }
Eric Laurent874c42872014-08-08 15:13:39 -07002920 for (size_t i = 0; i < patch->num_sinks; i++) {
2921 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2922 return INVALID_OPERATION;
2923 }
2924 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002925
2926 sp<AudioPatch> patchDesc;
2927 ssize_t index = mAudioPatches.indexOfKey(*handle);
2928
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2930 patch->sources[0].role,
2931 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002932#if LOG_NDEBUG == 0
2933 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002934 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002935 patch->sinks[i].role,
2936 patch->sinks[i].type);
2937 }
2938#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002939
2940 if (index >= 0) {
2941 patchDesc = mAudioPatches.valueAt(index);
2942 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2943 mUidCached, patchDesc->mUid, uid);
2944 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2945 return INVALID_OPERATION;
2946 }
2947 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002948 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 }
2950
2951 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002952 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002953 if (outputDesc == NULL) {
2954 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2955 return BAD_VALUE;
2956 }
Eric Laurent84c70242014-06-23 08:46:27 -07002957 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2958 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002959 if (patchDesc != 0) {
2960 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2961 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2962 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2963 return BAD_VALUE;
2964 }
2965 }
Eric Laurent874c42872014-08-08 15:13:39 -07002966 DeviceVector devices;
2967 for (size_t i = 0; i < patch->num_sinks; i++) {
2968 // Only support mix to devices connection
2969 // TODO add support for mix to mix connection
2970 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2971 ALOGV("createAudioPatch() source mix but sink is not a device");
2972 return INVALID_OPERATION;
2973 }
2974 sp<DeviceDescriptor> devDesc =
2975 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2976 if (devDesc == 0) {
2977 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2978 return BAD_VALUE;
2979 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002980
François Gaffie53615e22015-03-19 09:24:12 +01002981 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002982 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002983 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002984 NULL, // updatedSamplingRate
2985 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002986 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002987 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002988 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002989 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002990 ALOGV("createAudioPatch() profile not supported for device %08x",
2991 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002992 return INVALID_OPERATION;
2993 }
2994 devices.add(devDesc);
2995 }
2996 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 return INVALID_OPERATION;
2998 }
Eric Laurent874c42872014-08-08 15:13:39 -07002999
Eric Laurent6a94d692014-05-20 11:18:06 -07003000 // TODO: reconfigure output format and channels here
3001 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003002 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003003 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 index = mAudioPatches.indexOfKey(*handle);
3005 if (index >= 0) {
3006 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3007 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3008 }
3009 patchDesc = mAudioPatches.valueAt(index);
3010 patchDesc->mUid = uid;
3011 ALOGV("createAudioPatch() success");
3012 } else {
3013 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3014 return INVALID_OPERATION;
3015 }
3016 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3017 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3018 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003019 // only one sink supported when connecting an input device to a mix
3020 if (patch->num_sinks > 1) {
3021 return INVALID_OPERATION;
3022 }
François Gaffie53615e22015-03-19 09:24:12 +01003023 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003024 if (inputDesc == NULL) {
3025 return BAD_VALUE;
3026 }
3027 if (patchDesc != 0) {
3028 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3029 return BAD_VALUE;
3030 }
3031 }
3032 sp<DeviceDescriptor> devDesc =
3033 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3034 if (devDesc == 0) {
3035 return BAD_VALUE;
3036 }
3037
François Gaffie53615e22015-03-19 09:24:12 +01003038 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003039 devDesc->mAddress,
3040 patch->sinks[0].sample_rate,
3041 NULL, /*updatedSampleRate*/
3042 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003043 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003044 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003045 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003046 // FIXME for the parameter type,
3047 // and the NONE
3048 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003049 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 return INVALID_OPERATION;
3051 }
3052 // TODO: reconfigure output format and channels here
3053 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003054 devDesc->type(), inputDesc->mIoHandle);
3055 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003056 index = mAudioPatches.indexOfKey(*handle);
3057 if (index >= 0) {
3058 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3059 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3060 }
3061 patchDesc = mAudioPatches.valueAt(index);
3062 patchDesc->mUid = uid;
3063 ALOGV("createAudioPatch() success");
3064 } else {
3065 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3066 return INVALID_OPERATION;
3067 }
3068 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3069 // device to device connection
3070 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003071 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 return BAD_VALUE;
3073 }
3074 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003075 sp<DeviceDescriptor> srcDeviceDesc =
3076 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003077 if (srcDeviceDesc == 0) {
3078 return BAD_VALUE;
3079 }
Eric Laurent874c42872014-08-08 15:13:39 -07003080
Eric Laurent6a94d692014-05-20 11:18:06 -07003081 //update source and sink with our own data as the data passed in the patch may
3082 // be incomplete.
3083 struct audio_patch newPatch = *patch;
3084 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003085
Eric Laurent874c42872014-08-08 15:13:39 -07003086 for (size_t i = 0; i < patch->num_sinks; i++) {
3087 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3088 ALOGV("createAudioPatch() source device but one sink is not a device");
3089 return INVALID_OPERATION;
3090 }
3091
3092 sp<DeviceDescriptor> sinkDeviceDesc =
3093 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3094 if (sinkDeviceDesc == 0) {
3095 return BAD_VALUE;
3096 }
3097 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3098
Eric Laurent3bcf8592015-04-03 12:13:24 -07003099 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003100 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003101 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003102 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003103 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003104 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003105 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003106 return INVALID_OPERATION;
3107 }
Eric Laurent874c42872014-08-08 15:13:39 -07003108 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003109 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003110 // if the sink device is reachable via an opened output stream, request to go via
3111 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003112 audio_io_handle_t output = selectOutput(outputs,
3113 AUDIO_OUTPUT_FLAG_NONE,
3114 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003115 if (output != AUDIO_IO_HANDLE_NONE) {
3116 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3117 if (outputDesc->isDuplicated()) {
3118 return INVALID_OPERATION;
3119 }
3120 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003121 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003122 newPatch.num_sources = 2;
3123 }
Eric Laurent83b88082014-06-20 18:31:16 -07003124 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003125 }
3126 // TODO: check from routing capabilities in config file and other conflicting patches
3127
Mikhail Naganovdc769682018-05-04 15:34:08 -07003128 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3129 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003130 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3131 status);
3132 return INVALID_OPERATION;
3133 }
3134 } else {
3135 return BAD_VALUE;
3136 }
3137 } else {
3138 return BAD_VALUE;
3139 }
3140 return NO_ERROR;
3141}
3142
3143status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3144 uid_t uid)
3145{
3146 ALOGV("releaseAudioPatch() patch %d", handle);
3147
3148 ssize_t index = mAudioPatches.indexOfKey(handle);
3149
3150 if (index < 0) {
3151 return BAD_VALUE;
3152 }
3153 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3154 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3155 mUidCached, patchDesc->mUid, uid);
3156 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3157 return INVALID_OPERATION;
3158 }
3159
3160 struct audio_patch *patch = &patchDesc->mPatch;
3161 patchDesc->mUid = mUidCached;
3162 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003163 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 if (outputDesc == NULL) {
3165 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3166 return BAD_VALUE;
3167 }
3168
Eric Laurentc75307b2015-03-17 15:29:32 -07003169 setOutputDevice(outputDesc,
3170 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003171 true,
3172 0,
3173 NULL);
3174 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3175 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003176 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 if (inputDesc == NULL) {
3178 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3179 return BAD_VALUE;
3180 }
3181 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003182 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003183 true,
3184 NULL);
3185 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003186 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3187 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3188 status, patchDesc->mAfPatchHandle);
3189 removeAudioPatch(patchDesc->mHandle);
3190 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003191 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003192 } else {
3193 return BAD_VALUE;
3194 }
3195 } else {
3196 return BAD_VALUE;
3197 }
3198 return NO_ERROR;
3199}
3200
3201status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3202 struct audio_patch *patches,
3203 unsigned int *generation)
3204{
François Gaffie53615e22015-03-19 09:24:12 +01003205 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003206 return BAD_VALUE;
3207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003208 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003209 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003210}
3211
Eric Laurente1715a42014-05-20 11:30:42 -07003212status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003213{
Eric Laurente1715a42014-05-20 11:30:42 -07003214 ALOGV("setAudioPortConfig()");
3215
3216 if (config == NULL) {
3217 return BAD_VALUE;
3218 }
3219 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3220 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003221 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3222 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003223 }
3224
Eric Laurenta121f902014-06-03 13:32:54 -07003225 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003226 if (config->type == AUDIO_PORT_TYPE_MIX) {
3227 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003228 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003229 if (outputDesc == NULL) {
3230 return BAD_VALUE;
3231 }
Eric Laurent84c70242014-06-23 08:46:27 -07003232 ALOG_ASSERT(!outputDesc->isDuplicated(),
3233 "setAudioPortConfig() called on duplicated output %d",
3234 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003235 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003236 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003237 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003238 if (inputDesc == NULL) {
3239 return BAD_VALUE;
3240 }
Eric Laurenta121f902014-06-03 13:32:54 -07003241 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003242 } else {
3243 return BAD_VALUE;
3244 }
3245 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3246 sp<DeviceDescriptor> deviceDesc;
3247 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3248 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3249 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3250 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3251 } else {
3252 return BAD_VALUE;
3253 }
3254 if (deviceDesc == NULL) {
3255 return BAD_VALUE;
3256 }
Eric Laurenta121f902014-06-03 13:32:54 -07003257 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003258 } else {
3259 return BAD_VALUE;
3260 }
3261
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003262 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003263 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3264 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003265 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003266 audioPortConfig->toAudioPortConfig(&newConfig, config);
3267 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003268 }
Eric Laurenta121f902014-06-03 13:32:54 -07003269 if (status != NO_ERROR) {
3270 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003271 }
Eric Laurente1715a42014-05-20 11:30:42 -07003272
3273 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003274}
3275
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003276void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3277{
Eric Laurentd60560a2015-04-10 11:31:20 -07003278 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003279 clearAudioPatches(uid);
3280 clearSessionRoutes(uid);
3281}
3282
Eric Laurent6a94d692014-05-20 11:18:06 -07003283void AudioPolicyManager::clearAudioPatches(uid_t uid)
3284{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003285 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003286 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3287 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003288 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003289 }
3290 }
3291}
3292
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003293void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3294 audio_io_handle_t ouptutToSkip)
3295{
3296 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3297 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3298 for (size_t j = 0; j < mOutputs.size(); j++) {
3299 if (mOutputs.keyAt(j) == ouptutToSkip) {
3300 continue;
3301 }
3302 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3303 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3304 continue;
3305 }
3306 // If the default device for this strategy is on another output mix,
3307 // invalidate all tracks in this strategy to force re connection.
3308 // Otherwise select new device on the output mix.
3309 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003310 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003311 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3312 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3313 }
3314 }
3315 } else {
3316 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3317 setOutputDevice(outputDesc, newDevice, false);
3318 }
3319 }
3320}
3321
3322void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3323{
3324 // remove output routes associated with this uid
3325 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003326 for (size_t i = 0; i < mOutputs.size(); i++) {
3327 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003328 for (const auto& client : outputDesc->getClientIterable()) {
3329 if (client->hasPreferredDevice() && client->uid() == uid) {
3330 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3331 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003332 }
3333 }
3334 }
3335 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003336 for (const auto& strategy : affectedStrategies) {
3337 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003338 }
3339
3340 // remove input routes associated with this uid
3341 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003342 for (size_t i = 0; i < mInputs.size(); i++) {
3343 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003344 for (const auto& client : inputDesc->getClientIterable()) {
3345 if (client->hasPreferredDevice() && client->uid() == uid) {
3346 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3347 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348 }
3349 }
3350 }
3351 // reroute inputs if necessary
3352 SortedVector<audio_io_handle_t> inputsToClose;
3353 for (size_t i = 0; i < mInputs.size(); i++) {
3354 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003355 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003356 inputsToClose.add(inputDesc->mIoHandle);
3357 }
3358 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003359 for (const auto& input : inputsToClose) {
3360 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361 }
3362}
3363
Eric Laurentd60560a2015-04-10 11:31:20 -07003364void AudioPolicyManager::clearAudioSources(uid_t uid)
3365{
3366 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003367 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3368 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003369 stopAudioSource(mAudioSources.keyAt(i));
3370 }
3371 }
3372}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003373
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003374status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3375 audio_io_handle_t *ioHandle,
3376 audio_devices_t *device)
3377{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003378 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3379 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003380 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003381
François Gaffiedf372692015-03-19 10:43:27 +01003382 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003383}
3384
Eric Laurentd60560a2015-04-10 11:31:20 -07003385status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003386 const audio_attributes_t *attributes,
3387 audio_port_handle_t *portId,
3388 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003389{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003390 ALOGV("%s", __FUNCTION__);
3391 *portId = AUDIO_PORT_HANDLE_NONE;
3392
3393 if (source == NULL || attributes == NULL || portId == NULL) {
3394 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3395 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 return BAD_VALUE;
3397 }
3398
Eric Laurentd60560a2015-04-10 11:31:20 -07003399 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3400 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003401 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3402 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003403 return INVALID_OPERATION;
3404 }
3405
3406 sp<DeviceDescriptor> srcDeviceDesc =
3407 mAvailableInputDevices.getDevice(source->ext.device.type,
3408 String8(source->ext.device.address));
3409 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003410 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003411 return BAD_VALUE;
3412 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003413
3414 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003415
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003416 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003417 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418
3419 sp<SourceClientDescriptor> sourceDesc =
3420 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003421 streamTypefromAttributesInt(attributes),
3422 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003423
3424 status_t status = connectAudioSource(sourceDesc);
3425 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003426 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003427 }
3428 return status;
3429}
3430
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003431status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003432{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003433 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003434
3435 // make sure we only have one patch per source.
3436 disconnectAudioSource(sourceDesc);
3437
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003438 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003439 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003440 audio_stream_type_t stream = sourceDesc->stream();
3441 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003442
3443 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3444 sp<DeviceDescriptor> sinkDeviceDesc =
3445 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3446
3447 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003448
3449 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3450 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003451 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003452 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3453 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3454 // create patch between src device and output device
3455 // create Hwoutput and add to mHwOutputs
3456 } else {
3457 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3458 audio_io_handle_t output =
3459 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3460 if (output == AUDIO_IO_HANDLE_NONE) {
3461 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3462 return INVALID_OPERATION;
3463 }
3464 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3465 if (outputDesc->isDuplicated()) {
3466 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3467 return INVALID_OPERATION;
3468 }
Eric Laurent733ce942017-12-07 12:18:25 -08003469 status_t status = outputDesc->start();
3470 if (status != NO_ERROR) {
3471 return status;
3472 }
3473
Eric Laurentd60560a2015-04-10 11:31:20 -07003474 // create a special patch with no sink and two sources:
3475 // - the second source indicates to PatchPanel through which output mix this patch should
3476 // be connected as well as the stream type for volume control
3477 // - the sink is defined by whatever output device is currently selected for the output
3478 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003479 PatchBuilder patchBuilder;
3480 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3481 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003482 &afPatchHandle,
3483 0);
3484 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3485 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003486 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003487 if (status != NO_ERROR) {
3488 ALOGW("%s patch panel could not connect device patch, error %d",
3489 __FUNCTION__, status);
3490 return INVALID_OPERATION;
3491 }
3492 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003493 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003494
3495 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003496 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003497 return status;
3498 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003500 if (delayMs != 0) {
3501 usleep(delayMs * 1000);
3502 }
3503 }
3504
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3506 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003507
3508 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003509}
3510
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003511status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003512{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3514 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003515 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003516 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003517 return BAD_VALUE;
3518 }
3519 status_t status = disconnectAudioSource(sourceDesc);
3520
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003521 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003522 return status;
3523}
3524
Andy Hung2ddee192015-12-18 17:34:44 -08003525status_t AudioPolicyManager::setMasterMono(bool mono)
3526{
3527 if (mMasterMono == mono) {
3528 return NO_ERROR;
3529 }
3530 mMasterMono = mono;
3531 // if enabling mono we close all offloaded devices, which will invalidate the
3532 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3533 // for recreating the new AudioTrack as non-offloaded PCM.
3534 //
3535 // If disabling mono, we leave all tracks as is: we don't know which clients
3536 // and tracks are able to be recreated as offloaded. The next "song" should
3537 // play back offloaded.
3538 if (mMasterMono) {
3539 Vector<audio_io_handle_t> offloaded;
3540 for (size_t i = 0; i < mOutputs.size(); ++i) {
3541 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3542 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3543 offloaded.push(desc->mIoHandle);
3544 }
3545 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003546 for (const auto& handle : offloaded) {
3547 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003548 }
3549 }
3550 // update master mono for all remaining outputs
3551 for (size_t i = 0; i < mOutputs.size(); ++i) {
3552 updateMono(mOutputs.keyAt(i));
3553 }
3554 return NO_ERROR;
3555}
3556
3557status_t AudioPolicyManager::getMasterMono(bool *mono)
3558{
3559 *mono = mMasterMono;
3560 return NO_ERROR;
3561}
3562
Eric Laurentac9cef52017-06-09 15:46:26 -07003563float AudioPolicyManager::getStreamVolumeDB(
3564 audio_stream_type_t stream, int index, audio_devices_t device)
3565{
3566 return computeVolume(stream, index, device);
3567}
3568
jiabin81772902018-04-02 17:52:27 -07003569status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3570 audio_format_t *surroundFormats,
3571 bool *surroundFormatsEnabled,
3572 bool reported)
3573{
3574 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3575 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3576 return BAD_VALUE;
3577 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003578 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3579 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003580
3581 // Only return value if there is HDMI output.
3582 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3583 return INVALID_OPERATION;
3584 }
3585
3586 size_t formatsWritten = 0;
3587 size_t formatsMax = *numSurroundFormats;
3588 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003589 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003590 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003591 // Return formats from HDMI profiles, that have already been resolved by
3592 // checkOutputsForDevice().
3593 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3594 AUDIO_DEVICE_OUT_HDMI);
3595 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3596 FormatVector supportedFormats =
3597 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3598 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003599 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003600 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003601 } else {
3602 for (const auto& pair : mConfig.getSurroundFormats()) {
3603 if (pair.second.count(supportedFormats[j]) != 0) {
3604 formats.insert(pair.first);
3605 break;
3606 }
3607 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003608 }
3609 }
jiabin81772902018-04-02 17:52:27 -07003610 }
3611 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003612 for (const auto& pair : mConfig.getSurroundFormats()) {
3613 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003614 }
3615 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003616 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003617 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003618 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003619 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003620 if (mConfig.getSurroundFormats().count(format) == 0) {
3621 // Check sub-formats
3622 for (const auto& pair : mConfig.getSurroundFormats()) {
3623 for (const auto& subformat : pair.second) {
3624 formatEnabled = mSurroundFormats.count(subformat) != 0;
3625 if (formatEnabled) break;
3626 }
3627 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003628 }
3629 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003630 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003631 }
3632 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3633 }
3634 (*numSurroundFormats)++;
3635 }
3636 return NO_ERROR;
3637}
3638
3639status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3640{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003641 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003642 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003643 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3644 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003645 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003646 return BAD_VALUE;
3647 }
3648
3649 // Should only be called when MANUAL.
3650 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3651 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3652 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003653 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003654 return INVALID_OPERATION;
3655 }
3656
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003657 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003658 return NO_ERROR;
3659 }
3660
3661 // The operation is valid only when there is HDMI output available.
3662 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003663 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003664 return INVALID_OPERATION;
3665 }
3666
Mikhail Naganov2563f232018-09-27 14:48:01 -07003667 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003668 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003669 mSurroundFormats.insert(audioFormat);
3670 for (const auto& subFormat : formatIter->second) {
3671 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003672 }
3673 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003674 mSurroundFormats.erase(audioFormat);
3675 for (const auto& subFormat : formatIter->second) {
3676 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003677 }
3678 }
3679
3680 sp<SwAudioOutputDescriptor> outputDesc;
3681 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003682 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003683 AUDIO_DEVICE_OUT_HDMI);
3684 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3685 // Simulate reconnection to update enabled surround sound formats.
3686 String8 address = hdmiOutputDevices[i]->mAddress;
3687 String8 name = hdmiOutputDevices[i]->getName();
3688 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3689 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3690 address.c_str(),
3691 name.c_str());
3692 if (status != NO_ERROR) {
3693 continue;
3694 }
3695 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3696 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3697 address.c_str(),
3698 name.c_str());
3699 profileUpdated |= (status == NO_ERROR);
3700 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003701 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003702 AUDIO_DEVICE_IN_HDMI);
3703 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3704 // Simulate reconnection to update enabled surround sound formats.
3705 String8 address = hdmiInputDevices[i]->mAddress;
3706 String8 name = hdmiInputDevices[i]->getName();
3707 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3708 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3709 address.c_str(),
3710 name.c_str());
3711 if (status != NO_ERROR) {
3712 continue;
3713 }
3714 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3715 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3716 address.c_str(),
3717 name.c_str());
3718 profileUpdated |= (status == NO_ERROR);
3719 }
3720
jiabin81772902018-04-02 17:52:27 -07003721 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003722 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003723 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003724 }
3725
3726 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3727}
3728
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003729void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3730{
3731 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3732
3733 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3734 for (size_t i = 0; i < activeInputs.size(); i++) {
3735 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003736 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3737 for (const auto& client : clients) {
3738 if (uid == client->uid()) {
3739 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003740 }
3741 }
3742 }
3743}
3744
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003745status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003746{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003747 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003748
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003749 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003750 if (patchDesc == 0) {
3751 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003752 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003753 return BAD_VALUE;
3754 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003755 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003756
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003757 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003758 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003759 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003760 if (status == NO_ERROR) {
3761 swOutputDesc->stop();
3762 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003763 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3764 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003765 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003766 if (hwOutputDesc != 0) {
3767 // release patch between src device and output device
3768 // close Hwoutput and remove from mHwOutputs
3769 } else {
3770 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3771 }
3772 }
3773 return NO_ERROR;
3774}
3775
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003777 audio_io_handle_t output, routing_strategy strategy)
3778{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003779 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003780 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003781 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3782 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003783 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003784 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003785 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3786 source = sourceDesc;
3787 break;
3788 }
3789 }
3790 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003791}
3792
Eric Laurente552edb2014-03-10 17:42:56 -07003793// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003794// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003795// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003796uint32_t AudioPolicyManager::nextAudioPortGeneration()
3797{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003798 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003799}
3800
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003801#ifdef USE_XML_AUDIO_POLICY_CONF
3802// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3803static const char *kConfigLocationList[] =
3804 {"/odm/etc", "/vendor/etc", "/system/etc"};
3805static const int kConfigLocationListSize =
3806 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3807
3808static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3809 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003810 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003811 status_t ret;
3812
Petri Gyntherf497f292018-04-17 18:46:10 -07003813 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3814 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3815 // A2DP offload supported but disabled: try to use special XML file
3816 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3817 }
3818 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3819
3820 for (const char* fileName : fileNames) {
3821 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003822 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3823 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003824 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003825 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003826 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003827 return ret;
3828 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003829 }
3830 }
3831 return ret;
3832}
3833#endif
3834
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003835AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3836 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003837 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003838 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003839 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003840 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003841 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003842#ifdef USE_XML_AUDIO_POLICY_CONF
3843 mVolumeCurves(new VolumeCurvesCollection()),
3844 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003845 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003846#else
3847 mVolumeCurves(new StreamDescriptorCollection()),
3848 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3849 mDefaultOutputDevice),
3850#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003851 mAudioPortGeneration(1),
3852 mBeaconMuteRefCount(0),
3853 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003854 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003855 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003856 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003857 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3858 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003859{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003860}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003861
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003862AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3863 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3864{
3865 loadConfig();
3866 initialize();
3867}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003870#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003871 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3874 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003875#endif
3876 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003877 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003878 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003879}
3880
3881status_t AudioPolicyManager::initialize() {
3882 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003883
3884 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003885 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3886 if (!engineInstance) {
3887 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003889 }
3890 // Retrieve the Policy Manager Interface
3891 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3892 if (mEngine == NULL) {
3893 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003895 }
3896 mEngine->setObserver(this);
3897 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003898 if (status != NO_ERROR) {
3899 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3900 return status;
3901 }
François Gaffie2110e042015-03-24 08:41:51 +01003902
Eric Laurent3a4311c2014-03-17 12:00:47 -07003903 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003904 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003905 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3906 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003907 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003908 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003909 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3910 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003911 continue;
3912 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003913 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003914 // open all output streams needed to access attached devices
3915 // except for direct output streams that are only opened when they are actually
3916 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003918 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003919 if (!outProfile->canOpenNewIo()) {
3920 ALOGE("Invalid Output profile max open count %u for profile %s",
3921 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3922 continue;
3923 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003924 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003925 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003926 continue;
3927 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003928 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003929 mTtsOutputAvailable = true;
3930 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003931
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003932 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003933 continue;
3934 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003936 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3937 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003938 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003939 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003940 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003941 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003942 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 if ((profileType & outputDeviceTypes) == 0) {
3944 continue;
3945 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003946 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3947 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003948 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003949 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3950 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003951 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3952 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003953 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003954 status_t status = outputDesc->open(nullptr, profileType, address,
3955 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003956
3957 if (status != NO_ERROR) {
3958 ALOGW("Cannot open output stream for device %08x on hw module %s",
3959 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003960 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003961 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003962 for (const auto& dev : supportedDevices) {
3963 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003964 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003965 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003966 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003967 }
3968 }
3969 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003970 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003971 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003972 }
3973 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003975 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003976 true,
3977 0,
3978 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003979 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 }
Eric Laurente552edb2014-03-10 17:42:56 -07003981 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003982 // open input streams needed to access attached devices to validate
3983 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003984 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003985 if (!inProfile->canOpenNewIo()) {
3986 ALOGE("Invalid Input profile max open count %u for profile %s",
3987 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3988 continue;
3989 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003991 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003992 continue;
3993 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003994 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003995 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003996 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3997
Eric Laurentd78f1532014-09-16 16:38:20 -07003998 if ((profileType & inputDeviceTypes) == 0) {
3999 continue;
4000 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004001 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004002 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004003
Mikhail Naganov708e0382018-05-30 09:53:04 -07004004 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004005 // the inputs vector must be of size >= 1, but we don't want to crash here
4006 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4007 : String8("");
4008 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4009 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4010
Eric Laurentd78f1532014-09-16 16:38:20 -07004011 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004012 status_t status = inputDesc->open(nullptr,
4013 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004014 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004015 AUDIO_SOURCE_MIC,
4016 AUDIO_INPUT_FLAG_NONE,
4017 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004018
4019 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004020 for (const auto& dev : inProfile->getSupportedDevices()) {
4021 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004023 if (index >= 0) {
4024 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4025 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004026 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004027 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004028 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004029 }
4030 }
Eric Laurentfe231122017-11-17 17:48:06 -08004031 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004032 } else {
4033 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004034 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004035 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004036 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004037 }
4038 }
4039 // make sure all attached devices have been allocated a unique ID
4040 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004041 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004042 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4044 continue;
4045 }
François Gaffie2110e042015-03-24 08:41:51 +01004046 // The device is now validated and can be appended to the available devices of the engine
4047 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4048 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 i++;
4050 }
4051 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004052 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004053 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4055 continue;
4056 }
François Gaffie2110e042015-03-24 08:41:51 +01004057 // The device is now validated and can be appended to the available devices of the engine
4058 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4059 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 i++;
4061 }
4062 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004064 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004065 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 }
jiabin9ff780e2018-03-19 18:19:52 -07004067 // If microphones address is empty, set it according to device type
4068 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4069 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4070 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4071 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4072 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4073 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4074 }
4075 }
4076 }
Eric Laurente552edb2014-03-10 17:42:56 -07004077
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004078 if (mPrimaryOutput == 0) {
4079 ALOGE("Failed to open primary output");
4080 status = NO_INIT;
4081 }
Eric Laurente552edb2014-03-10 17:42:56 -07004082
4083 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004084 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004085}
4086
Eric Laurente0720872014-03-11 09:30:41 -07004087AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004088{
Eric Laurente552edb2014-03-10 17:42:56 -07004089 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004090 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004091 }
4092 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004093 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004094 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004095 mAvailableOutputDevices.clear();
4096 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004097 mOutputs.clear();
4098 mInputs.clear();
4099 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004100 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004101 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004102}
4103
Eric Laurente0720872014-03-11 09:30:41 -07004104status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004105{
Eric Laurent87ffa392015-05-22 10:32:38 -07004106 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004107}
4108
Eric Laurente552edb2014-03-10 17:42:56 -07004109// ---
4110
Eric Laurent98e38192018-02-15 18:31:53 -08004111void AudioPolicyManager::addOutput(audio_io_handle_t output,
4112 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004113{
Eric Laurent1c333e22014-05-20 10:48:17 -07004114 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004115 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004116 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004117 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004118 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004119}
4120
François Gaffie53615e22015-03-19 09:24:12 +01004121void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4122{
4123 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004124 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004125}
4126
Eric Laurent98e38192018-02-15 18:31:53 -08004127void AudioPolicyManager::addInput(audio_io_handle_t input,
4128 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004129{
Eric Laurent1c333e22014-05-20 10:48:17 -07004130 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004131 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004132}
Eric Laurente552edb2014-03-10 17:42:56 -07004133
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004134void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004135 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004136 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004137 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004138 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004139 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004140 if (devDesc != 0) {
4141 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4142 desc->mIoHandle, address.string());
4143 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004144 }
4145}
4146
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004147status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004148 audio_policy_dev_state_t state,
4149 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004150 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004151{
François Gaffie53615e22015-03-19 09:24:12 +01004152 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004153 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004154
4155 if (audio_device_is_digital(device)) {
4156 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004157 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004158 }
Eric Laurente552edb2014-03-10 17:42:56 -07004159
Eric Laurent3b73df72014-03-11 09:06:29 -07004160 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004161 // first list already open outputs that can be routed to this device
4162 for (size_t i = 0; i < mOutputs.size(); i++) {
4163 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004164 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004165 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004166 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4167 outputs.add(mOutputs.keyAt(i));
4168 } else {
4169 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004170 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004171 }
Eric Laurente552edb2014-03-10 17:42:56 -07004172 }
4173 }
4174 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004175 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004176 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004177 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4178 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004179 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004180 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004181 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004182 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004183 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4184 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004185 }
Eric Laurente552edb2014-03-10 17:42:56 -07004186 }
4187 }
4188 }
4189
Eric Laurent7b279bb2015-12-14 10:18:23 -08004190 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004191
Eric Laurente552edb2014-03-10 17:42:56 -07004192 if (profiles.isEmpty() && outputs.isEmpty()) {
4193 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4194 return BAD_VALUE;
4195 }
4196
4197 // open outputs for matching profiles if needed. Direct outputs are also opened to
4198 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4199 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004200 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004201
4202 // nothing to do if one output is already opened for this profile
4203 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004204 for (j = 0; j < outputs.size(); j++) {
4205 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004206 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004207 // matching profile: save the sample rates, format and channel masks supported
4208 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004209 if (audio_device_is_digital(device)) {
4210 devDesc->importAudioPort(profile);
4211 }
Eric Laurente552edb2014-03-10 17:42:56 -07004212 break;
4213 }
4214 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004215 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004216 continue;
4217 }
4218
Eric Laurent3974e3b2017-12-07 17:58:43 -08004219 if (!profile->canOpenNewIo()) {
4220 ALOGW("Max Output number %u already opened for this profile %s",
4221 profile->maxOpenCount, profile->getTagName().c_str());
4222 continue;
4223 }
4224
Eric Laurent83efe1c2017-07-09 16:51:08 -07004225 ALOGV("opening output for device %08x with params %s profile %p name %s",
4226 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004227 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004228 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004229 status_t status = desc->open(nullptr, device, address,
4230 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004231
Eric Laurentfe231122017-11-17 17:48:06 -08004232 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004233 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004234 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004235 char *param = audio_device_address_to_parameter(device, address);
4236 mpClientInterface->setParameters(output, String8(param));
4237 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004238 }
Phil Burk00eeb322016-03-31 12:41:00 -07004239 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004240 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004241 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004242 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004243 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004244 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004245 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004246 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004247 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4248 profile->pickAudioProfile(
4249 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004250 config.offload_info.sample_rate = config.sample_rate;
4251 config.offload_info.channel_mask = config.channel_mask;
4252 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004253
4254 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4255 AUDIO_OUTPUT_FLAG_NONE, &output);
4256 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004257 output = AUDIO_IO_HANDLE_NONE;
4258 }
Eric Laurentd4692962014-05-05 18:13:44 -07004259 }
4260
Eric Laurentcf2c0212014-07-25 16:20:43 -07004261 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004262 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004263 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004264 sp<AudioPolicyMix> policyMix;
4265 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004266 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4267 address.string());
4268 }
François Gaffie036e1e92015-03-19 10:16:24 +01004269 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004270 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004271
Eric Laurent87ffa392015-05-22 10:32:38 -07004272 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4273 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004274 // no duplicated output for direct outputs and
4275 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004276 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004277
Eric Laurentd4692962014-05-05 18:13:44 -07004278 //TODO: configure audio effect output stage here
4279
4280 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004281 sp<SwAudioOutputDescriptor> dupOutputDesc =
4282 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4283 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4284 &duplicatedOutput);
4285 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004286 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004287 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004288 } else {
4289 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004290 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004291 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004292 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004293 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004294 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004295 }
Eric Laurente552edb2014-03-10 17:42:56 -07004296 }
4297 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004298 } else {
4299 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004300 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004301 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004302 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004303 profiles.removeAt(profile_index);
4304 profile_index--;
4305 } else {
4306 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004307 // Load digital format info only for digital devices
4308 if (audio_device_is_digital(device)) {
4309 devDesc->importAudioPort(profile);
4310 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004311
François Gaffie53615e22015-03-19 09:24:12 +01004312 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004313 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4314 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004315 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004316 NULL/*patch handle*/, address.string());
4317 }
Eric Laurente552edb2014-03-10 17:42:56 -07004318 ALOGV("checkOutputsForDevice(): adding output %d", output);
4319 }
4320 }
4321
4322 if (profiles.isEmpty()) {
4323 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4324 return BAD_VALUE;
4325 }
Eric Laurentd4692962014-05-05 18:13:44 -07004326 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004327 // check if one opened output is not needed any more after disconnecting one device
4328 for (size_t i = 0; i < mOutputs.size(); i++) {
4329 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004330 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004331 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004332 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004333 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004334 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004335 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004336 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4337 mOutputs.keyAt(i));
4338 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004339 }
Eric Laurente552edb2014-03-10 17:42:56 -07004340 }
4341 }
Eric Laurentd4692962014-05-05 18:13:44 -07004342 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004343 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004344 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4345 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004346 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004347 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004348 "clearing direct output profile %zu on module %s",
4349 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004350 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004351 }
4352 }
4353 }
4354 }
4355 return NO_ERROR;
4356}
4357
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004358status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004359 audio_policy_dev_state_t state,
4360 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004361 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004362{
Paul McLean9080a4c2015-06-18 08:24:02 -07004363 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004364 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004365
4366 if (audio_device_is_digital(device)) {
4367 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004368 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004369 }
4370
Eric Laurentd4692962014-05-05 18:13:44 -07004371 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4372 // first list already open inputs that can be routed to this device
4373 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4374 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004375 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004376 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4377 inputs.add(mInputs.keyAt(input_index));
4378 }
4379 }
4380
4381 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004382 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004383 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004384 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004385 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004386 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004387 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004388
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004389 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004390 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004391 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004392 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004393 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4394 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004395 }
Eric Laurentd4692962014-05-05 18:13:44 -07004396 }
4397 }
4398 }
4399
4400 if (profiles.isEmpty() && inputs.isEmpty()) {
4401 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4402 return BAD_VALUE;
4403 }
4404
4405 // open inputs for matching profiles if needed. Direct inputs are also opened to
4406 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4407 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4408
Eric Laurent1c333e22014-05-20 10:48:17 -07004409 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004410
Eric Laurentd4692962014-05-05 18:13:44 -07004411 // nothing to do if one input is already opened for this profile
4412 size_t input_index;
4413 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4414 desc = mInputs.valueAt(input_index);
4415 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004416 if (audio_device_is_digital(device)) {
4417 devDesc->importAudioPort(profile);
4418 }
Eric Laurentd4692962014-05-05 18:13:44 -07004419 break;
4420 }
4421 }
4422 if (input_index != mInputs.size()) {
4423 continue;
4424 }
4425
Eric Laurent3974e3b2017-12-07 17:58:43 -08004426 if (!profile->canOpenNewIo()) {
4427 ALOGW("Max Input number %u already opened for this profile %s",
4428 profile->maxOpenCount, profile->getTagName().c_str());
4429 continue;
4430 }
4431
Eric Laurentfe231122017-11-17 17:48:06 -08004432 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004433 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004434 status_t status = desc->open(nullptr,
4435 device,
4436 address,
4437 AUDIO_SOURCE_MIC,
4438 AUDIO_INPUT_FLAG_NONE,
4439 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004440
Eric Laurentcf2c0212014-07-25 16:20:43 -07004441 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004442 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004443 char *param = audio_device_address_to_parameter(device, address);
4444 mpClientInterface->setParameters(input, String8(param));
4445 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004446 }
Phil Burk00eeb322016-03-31 12:41:00 -07004447 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004448 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004449 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004450 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004451 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004452 }
4453
4454 if (input != 0) {
4455 addInput(input, desc);
4456 }
4457 } // endif input != 0
4458
Eric Laurentcf2c0212014-07-25 16:20:43 -07004459 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004460 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004461 profiles.removeAt(profile_index);
4462 profile_index--;
4463 } else {
4464 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004465 if (audio_device_is_digital(device)) {
4466 devDesc->importAudioPort(profile);
4467 }
Eric Laurentd4692962014-05-05 18:13:44 -07004468 ALOGV("checkInputsForDevice(): adding input %d", input);
4469 }
4470 } // end scan profiles
4471
4472 if (profiles.isEmpty()) {
4473 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4474 return BAD_VALUE;
4475 }
4476 } else {
4477 // Disconnect
4478 // check if one opened input is not needed any more after disconnecting one device
4479 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4480 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004481 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004482 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4483 mInputs.keyAt(input_index));
4484 inputs.add(mInputs.keyAt(input_index));
4485 }
4486 }
4487 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004488 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004489 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004490 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004491 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004492 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004493 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004494 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4495 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004496 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004497 }
4498 }
4499 }
4500 } // end disconnect
4501
4502 return NO_ERROR;
4503}
4504
4505
Eric Laurente0720872014-03-11 09:30:41 -07004506void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004507{
4508 ALOGV("closeOutput(%d)", output);
4509
Eric Laurentc75307b2015-03-17 15:29:32 -07004510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004511 if (outputDesc == NULL) {
4512 ALOGW("closeOutput() unknown output %d", output);
4513 return;
4514 }
François Gaffie036e1e92015-03-19 10:16:24 +01004515 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004516
Eric Laurente552edb2014-03-10 17:42:56 -07004517 // look for duplicated outputs connected to the output being removed.
4518 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004519 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004520 if (dupOutputDesc->isDuplicated() &&
4521 (dupOutputDesc->mOutput1 == outputDesc ||
4522 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004523 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004524 if (dupOutputDesc->mOutput1 == outputDesc) {
4525 outputDesc2 = dupOutputDesc->mOutput2;
4526 } else {
4527 outputDesc2 = dupOutputDesc->mOutput1;
4528 }
4529 // As all active tracks on duplicated output will be deleted,
4530 // and as they were also referenced on the other output, the reference
4531 // count for their stream type must be adjusted accordingly on
4532 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004533 const bool wasActive = outputDesc2->isActive();
4534 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4535 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 }
Eric Laurent733ce942017-12-07 12:18:25 -08004537 // stop() will be a no op if the output is still active but is needed in case all
4538 // active streams refcounts where cleared above
4539 if (wasActive) {
4540 outputDesc2->stop();
4541 }
Eric Laurente552edb2014-03-10 17:42:56 -07004542 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4543 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4544
4545 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004546 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004547 }
4548 }
4549
Eric Laurent05b90f82014-08-27 15:32:29 -07004550 nextAudioPortGeneration();
4551
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004552 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004553 if (index >= 0) {
4554 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004555 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004556 mAudioPatches.removeItemsAt(index);
4557 mpClientInterface->onAudioPatchListUpdate();
4558 }
4559
Eric Laurentfe231122017-11-17 17:48:06 -08004560 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004561
François Gaffie53615e22015-03-19 09:24:12 +01004562 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004563 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004564
4565 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4566 // no direct outputs are open.
4567 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4568 bool directOutputOpen = false;
4569 for (size_t i = 0; i < mOutputs.size(); i++) {
4570 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4571 directOutputOpen = true;
4572 break;
4573 }
4574 }
4575 if (!directOutputOpen) {
4576 ALOGV("no direct outputs open, reset MSD patch");
4577 setMsdPatch();
4578 }
4579 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004580}
4581
4582void AudioPolicyManager::closeInput(audio_io_handle_t input)
4583{
4584 ALOGV("closeInput(%d)", input);
4585
4586 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4587 if (inputDesc == NULL) {
4588 ALOGW("closeInput() unknown input %d", input);
4589 return;
4590 }
4591
Eric Laurent6a94d692014-05-20 11:18:06 -07004592 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004593
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004594 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004595 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004596 if (index >= 0) {
4597 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004598 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004599 mAudioPatches.removeItemsAt(index);
4600 mpClientInterface->onAudioPatchListUpdate();
4601 }
4602
Eric Laurentfe231122017-11-17 17:48:06 -08004603 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004604 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004605
4606 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4607 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4608 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4609 SoundTrigger::setCaptureState(false);
4610 }
Eric Laurente552edb2014-03-10 17:42:56 -07004611}
4612
Eric Laurentc75307b2015-03-17 15:29:32 -07004613SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4614 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004615 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004616{
4617 SortedVector<audio_io_handle_t> outputs;
4618
4619 ALOGVV("getOutputsForDevice() device %04x", device);
4620 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004621 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004622 i, openOutputs.valueAt(i)->isDuplicated(),
4623 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004624 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4625 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4626 outputs.add(openOutputs.keyAt(i));
4627 }
4628 }
4629 return outputs;
4630}
4631
Mikhail Naganov37977152018-07-11 15:54:44 -07004632void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4633{
4634 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4635 // output is suspended before any tracks are moved to it
4636 checkA2dpSuspend();
4637 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004638 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004639 updateDevicesAndOutputs();
Mikhail Naganovf02f3672018-11-09 12:44:16 -08004640 if (getMsdModule() != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004641 setMsdPatch();
4642 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004643}
4644
Eric Laurente0720872014-03-11 09:30:41 -07004645void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004646{
4647 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4648 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4649 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4650 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4651
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004652 // also take into account external policy-related changes: add all outputs which are
4653 // associated with policies in the "before" and "after" output vectors
4654 ALOGVV("checkOutputForStrategy(): policy related outputs");
4655 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004656 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004657 if (desc != 0 && desc->mPolicyMix != NULL) {
4658 srcOutputs.add(desc->mIoHandle);
4659 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4660 }
4661 }
4662 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004663 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004664 if (desc != 0 && desc->mPolicyMix != NULL) {
4665 dstOutputs.add(desc->mIoHandle);
4666 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4667 }
4668 }
4669
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004670 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004671 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4672 // audio from invalidated tracks will be rendered when unmuting
4673 uint32_t maxLatency = 0;
4674 for (audio_io_handle_t srcOut : srcOutputs) {
4675 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4676 if (desc != 0 && maxLatency < desc->latency()) {
4677 maxLatency = desc->latency();
4678 }
4679 }
Eric Laurente552edb2014-03-10 17:42:56 -07004680 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4681 strategy, srcOutputs[0], dstOutputs[0]);
4682 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004683 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004684 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4685 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004686 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004687 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004688 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004689 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004690 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004691 if (source != 0){
4692 connectAudioSource(source);
4693 }
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695
4696 // Move effects associated to this strategy from previous output to new output
4697 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004698 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004699 }
4700 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004701 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004702 if (getStrategy((audio_stream_type_t)i) == strategy) {
4703 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004704 }
4705 }
4706 }
4707}
4708
Eric Laurente0720872014-03-11 09:30:41 -07004709void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004710{
François Gaffie2110e042015-03-24 08:41:51 +01004711 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004712 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004714 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004715 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004716 checkOutputForStrategy(STRATEGY_SONIFICATION);
4717 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004718 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004719 checkOutputForStrategy(STRATEGY_MEDIA);
4720 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004721 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004722}
4723
Eric Laurente0720872014-03-11 09:30:41 -07004724void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004725{
François Gaffie53615e22015-03-19 09:24:12 +01004726 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004727 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004728 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004729 return;
4730 }
4731
Eric Laurent3a4311c2014-03-17 12:00:47 -07004732 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004733 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4734 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4735 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004736
4737 // if suspended, restore A2DP output if:
4738 // ((SCO device is NOT connected) ||
4739 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4740 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004741 //
Eric Laurentf732e072016-08-03 19:30:28 -07004742 // if not suspended, suspend A2DP output if:
4743 // (SCO device is connected) &&
4744 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4745 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004746 //
4747 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004748 if (!isScoConnected ||
4749 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4750 AUDIO_POLICY_FORCE_BT_SCO) &&
4751 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4752 AUDIO_POLICY_FORCE_BT_SCO) &&
4753 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004754 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004755
4756 mpClientInterface->restoreOutput(a2dpOutput);
4757 mA2dpSuspended = false;
4758 }
4759 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004760 if (isScoConnected &&
4761 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4762 AUDIO_POLICY_FORCE_BT_SCO) ||
4763 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4764 AUDIO_POLICY_FORCE_BT_SCO) ||
4765 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004766 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004767
4768 mpClientInterface->suspendOutput(a2dpOutput);
4769 mA2dpSuspended = true;
4770 }
4771 }
4772}
4773
Eric Laurent97ac8712018-07-27 18:59:02 -07004774template <class IoDescriptor, class Filter>
4775sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4776 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4777{
4778 auto activeClients = desc->clientsList(true /*activeOnly*/);
4779 auto activeClientsWithRoute =
4780 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4781 active = activeClients.size() > 0;
4782 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4783 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4784 }
4785 return nullptr;
4786}
4787
4788template <class IoCollection, class Filter>
4789sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4790 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4791{
4792 sp<DeviceDescriptor> device;
4793 for (size_t i = 0; i < ioCollection.size(); i++) {
4794 auto desc = ioCollection.valueAt(i);
4795 bool active;
4796 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4797 if (active && curDevice == nullptr) {
4798 return nullptr;
4799 } else if (curDevice != nullptr) {
4800 device = curDevice;
4801 }
4802 }
4803 return device;
4804}
4805
Eric Laurentc75307b2015-03-17 15:29:32 -07004806audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4807 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004808{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004809 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004810 if (index >= 0) {
4811 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4812 if (patchDesc->mUid != mUidCached) {
4813 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004814 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 return outputDesc->device();
4816 }
4817 }
4818
Eric Laurent97ac8712018-07-27 18:59:02 -07004819 // Honor explicit routing requests only if no client using default routing is active on this
4820 // input: a specific app can not force routing for other apps by setting a preferred device.
4821 bool active; // unused
4822 sp<DeviceDescriptor> deviceDesc =
4823 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4824 if (deviceDesc != nullptr) {
4825 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004826 }
4827
Eric Laurente552edb2014-03-10 17:42:56 -07004828 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004829 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004830 // use device for strategy enforced audible
4831 // 2: we are in call or the strategy phone is active on the output:
4832 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004833 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004834 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004835 // 4: the strategy for enforced audible is active but not enforced on the output:
4836 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004837 // 5: the strategy accessibility is active on the output:
4838 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004839 // 6: the strategy "respectful" sonification is active on the output:
4840 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004841 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004842 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004843 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004844 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004845 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004846 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004847
4848 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4849 // with a refined rule considering mutually exclusive devices (using same backend)
4850 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004851 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004852 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004853 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4855 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004856 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004857 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004858 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004859 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004860 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4861 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004862 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4863 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004864 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004865 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004866 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004867 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004868 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004869 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004870 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004871 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004872 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004873 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004874 }
4875
Eric Laurent1c333e22014-05-20 10:48:17 -07004876 ALOGV("getNewOutputDevice() selected device %x", device);
4877 return device;
4878}
4879
Eric Laurentfb66dd92016-01-28 18:32:03 -08004880audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004881{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004882 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004883
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004884 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 if (index >= 0) {
4886 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4887 if (patchDesc->mUid != mUidCached) {
4888 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004889 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 return inputDesc->mDevice;
4891 }
4892 }
4893
Eric Laurent97ac8712018-07-27 18:59:02 -07004894 // Honor explicit routing requests only if no client using default routing is active on this
4895 // input: a specific app can not force routing for other apps by setting a preferred device.
4896 bool active;
4897 sp<DeviceDescriptor> deviceDesc =
4898 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4899 if (deviceDesc != nullptr) {
4900 return deviceDesc->type();
4901 }
4902
Eric Laurentdc95a252018-04-12 12:46:56 -07004903 // If we are not in call and no client is active on this input, this methods returns
4904 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004905 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004906 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4907 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4908 }
4909 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004910 device = getDeviceAndMixForInputSource(source);
4911 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004912
Eric Laurente552edb2014-03-10 17:42:56 -07004913 return device;
4914}
4915
Eric Laurent794fde22016-03-11 09:50:45 -08004916bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4917 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004918 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004919}
4920
Eric Laurente0720872014-03-11 09:30:41 -07004921uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004922 return (uint32_t)getStrategy(stream);
4923}
4924
Eric Laurente0720872014-03-11 09:30:41 -07004925audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004926 // By checking the range of stream before calling getStrategy, we avoid
4927 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4928 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004929 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 return AUDIO_DEVICE_NONE;
4931 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004932 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004933 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004934 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4935 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004936 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 }
Eric Laurent794fde22016-03-11 09:50:45 -08004938 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004939 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004940 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004941 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004942 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4943 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004944 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004945 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004946 }
4947 }
Eric Laurente552edb2014-03-10 17:42:56 -07004948 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004949
Eric Laurentb0688d62018-08-14 15:49:18 -07004950 // Favor devices selected on active streams if any to report correct device in case of
4951 // explicit device selection
4952 if (activeDevices != AUDIO_DEVICE_NONE) {
4953 devices = activeDevices;
4954 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004955 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4956 and doesn't really need to.*/
4957 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4958 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4959 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4960 }
Eric Laurente552edb2014-03-10 17:42:56 -07004961 return devices;
4962}
4963
François Gaffie2110e042015-03-24 08:41:51 +01004964routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4965{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004966 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004967 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004968}
4969
Eric Laurent97ac8712018-07-27 18:59:02 -07004970routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004971 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004972 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004973 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004974 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004975 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004976 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004977 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004978 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004979 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004980}
4981
Eric Laurente0720872014-03-11 09:30:41 -07004982void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004983 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004985 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4986 updateDevicesAndOutputs();
4987 break;
4988 default:
4989 break;
4990 }
4991}
4992
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004993uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004994
4995 // skip beacon mute management if a dedicated TTS output is available
4996 if (mTtsOutputAvailable) {
4997 return 0;
4998 }
4999
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005000 switch(event) {
5001 case STARTING_OUTPUT:
5002 mBeaconMuteRefCount++;
5003 break;
5004 case STOPPING_OUTPUT:
5005 if (mBeaconMuteRefCount > 0) {
5006 mBeaconMuteRefCount--;
5007 }
5008 break;
5009 case STARTING_BEACON:
5010 mBeaconPlayingRefCount++;
5011 break;
5012 case STOPPING_BEACON:
5013 if (mBeaconPlayingRefCount > 0) {
5014 mBeaconPlayingRefCount--;
5015 }
5016 break;
5017 }
5018
5019 if (mBeaconMuteRefCount > 0) {
5020 // any playback causes beacon to be muted
5021 return setBeaconMute(true);
5022 } else {
5023 // no other playback: unmute when beacon starts playing, mute when it stops
5024 return setBeaconMute(mBeaconPlayingRefCount == 0);
5025 }
5026}
5027
5028uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5029 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5030 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5031 // keep track of muted state to avoid repeating mute/unmute operations
5032 if (mBeaconMuted != mute) {
5033 // mute/unmute AUDIO_STREAM_TTS on all outputs
5034 ALOGV("\t muting %d", mute);
5035 uint32_t maxLatency = 0;
5036 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005037 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005038 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005039 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005040 0 /*delay*/, AUDIO_DEVICE_NONE);
5041 const uint32_t latency = desc->latency() * 2;
5042 if (latency > maxLatency) {
5043 maxLatency = latency;
5044 }
5045 }
5046 mBeaconMuted = mute;
5047 return maxLatency;
5048 }
5049 return 0;
5050}
5051
Eric Laurente0720872014-03-11 09:30:41 -07005052audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005053 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005054{
Eric Laurent97ac8712018-07-27 18:59:02 -07005055 // Honor explicit routing requests only if all active clients have a preferred route in which
5056 // case the last active client route is used
5057 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5058 if (deviceDesc != nullptr) {
5059 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005060 }
5061
Eric Laurente552edb2014-03-10 17:42:56 -07005062 if (fromCache) {
5063 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5064 strategy, mDeviceForStrategy[strategy]);
5065 return mDeviceForStrategy[strategy];
5066 }
François Gaffie2110e042015-03-24 08:41:51 +01005067 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005068}
5069
Eric Laurente0720872014-03-11 09:30:41 -07005070void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005071{
5072 for (int i = 0; i < NUM_STRATEGIES; i++) {
5073 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5074 }
5075 mPreviousOutputs = mOutputs;
5076}
5077
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005078uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005079 audio_devices_t prevDevice,
5080 uint32_t delayMs)
5081{
5082 // mute/unmute strategies using an incompatible device combination
5083 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5084 // if unmuting, unmute only after the specified delay
5085 if (outputDesc->isDuplicated()) {
5086 return 0;
5087 }
5088
5089 uint32_t muteWaitMs = 0;
5090 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005091 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005092
5093 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5094 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005095 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005096 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5097 bool doMute = false;
5098
5099 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5100 doMute = true;
5101 outputDesc->mStrategyMutedByDevice[i] = true;
5102 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5103 doMute = true;
5104 outputDesc->mStrategyMutedByDevice[i] = false;
5105 }
Eric Laurent99401132014-05-07 19:48:15 -07005106 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005107 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005108 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005109 // skip output if it does not share any device with current output
5110 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5111 == AUDIO_DEVICE_NONE) {
5112 continue;
5113 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005114 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005115 mute ? "muting" : "unmuting", i, curDevice);
5116 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005117 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005118 if (mute) {
5119 // FIXME: should not need to double latency if volume could be applied
5120 // immediately by the audioflinger mixer. We must account for the delay
5121 // between now and the next time the audioflinger thread for this output
5122 // will process a buffer (which corresponds to one buffer size,
5123 // usually 1/2 or 1/4 of the latency).
5124 if (muteWaitMs < desc->latency() * 2) {
5125 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005126 }
5127 }
5128 }
5129 }
5130 }
5131 }
5132
Eric Laurent99401132014-05-07 19:48:15 -07005133 // temporary mute output if device selection changes to avoid volume bursts due to
5134 // different per device volumes
5135 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005136 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5137 // temporary mute duration is conservatively set to 4 times the reported latency
5138 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5139 if (muteWaitMs < tempMuteWaitMs) {
5140 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005141 }
Eric Laurentdc462862016-07-19 12:29:53 -07005142
Eric Laurent99401132014-05-07 19:48:15 -07005143 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005144 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005145 // make sure that we do not start the temporary mute period too early in case of
5146 // delayed device change
5147 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005148 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005149 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005150 }
5151 }
5152 }
5153
Eric Laurente552edb2014-03-10 17:42:56 -07005154 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5155 if (muteWaitMs > delayMs) {
5156 muteWaitMs -= delayMs;
5157 usleep(muteWaitMs * 1000);
5158 return muteWaitMs;
5159 }
5160 return 0;
5161}
5162
Eric Laurentc75307b2015-03-17 15:29:32 -07005163uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005164 audio_devices_t device,
5165 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005167 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005168 const char *address,
5169 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005170{
Eric Laurentc75307b2015-03-17 15:29:32 -07005171 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005172 AudioParameter param;
5173 uint32_t muteWaitMs;
5174
5175 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005176 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5177 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5178 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5179 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005180 return muteWaitMs;
5181 }
5182 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5183 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005184 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005185 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005186 return 0;
5187 }
5188
5189 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005191
5192 audio_devices_t prevDevice = outputDesc->mDevice;
5193
Paul McLeanaa981192015-03-21 09:55:15 -07005194 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005195
5196 if (device != AUDIO_DEVICE_NONE) {
5197 outputDesc->mDevice = device;
5198 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005199
5200 // if the outputs are not materially active, there is no need to mute.
5201 if (requiresMuteCheck) {
5202 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5203 } else {
5204 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5205 muteWaitMs = 0;
5206 }
Eric Laurente552edb2014-03-10 17:42:56 -07005207
5208 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005209 // the requested device is AUDIO_DEVICE_NONE
5210 // OR the requested device is the same as current device
5211 // AND force is not specified
5212 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005213 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005214 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5215 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005216 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005218 return muteWaitMs;
5219 }
5220
5221 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005222
Eric Laurente552edb2014-03-10 17:42:56 -07005223 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005224 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005226 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005227 DeviceVector deviceList;
5228 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005229 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005230 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005231 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5232 device, String8(address));
5233 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005234 }
5235
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005237 PatchBuilder patchBuilder;
5238 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005240 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005242 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005243 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005244
5245 // inform all input as well
5246 for (size_t i = 0; i < mInputs.size(); i++) {
5247 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005248 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005249 AudioParameter inputCmd = AudioParameter();
5250 ALOGV("%s: inform input %d of device:%d", __func__,
5251 inputDescriptor->mIoHandle, device);
5252 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5253 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5254 inputCmd.toString(),
5255 delayMs);
5256 }
5257 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 }
Eric Laurente552edb2014-03-10 17:42:56 -07005259
5260 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005261 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005262
5263 return muteWaitMs;
5264}
5265
Eric Laurentc75307b2015-03-17 15:29:32 -07005266status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 int delayMs,
5268 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005269{
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 ssize_t index;
5271 if (patchHandle) {
5272 index = mAudioPatches.indexOfKey(*patchHandle);
5273 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005274 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 }
5276 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005277 return INVALID_OPERATION;
5278 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5280 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005281 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005282 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 removeAudioPatch(patchDesc->mHandle);
5284 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005285 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 return status;
5287}
5288
5289status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5290 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 bool force,
5292 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005293{
5294 status_t status = NO_ERROR;
5295
Eric Laurent1f2f2232014-06-02 12:01:23 -07005296 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5298 inputDesc->mDevice = device;
5299
Mikhail Naganov708e0382018-05-30 09:53:04 -07005300 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005301 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005302 PatchBuilder patchBuilder;
5303 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005304 // AUDIO_SOURCE_HOTWORD is for internal use only:
5305 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005306 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5307 auto result = usecase;
5308 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5309 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5310 }
5311 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005312 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005313 addSource(deviceList.itemAt(0));
5314 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005315 }
5316 }
5317 return status;
5318}
5319
Eric Laurent6a94d692014-05-20 11:18:06 -07005320status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5321 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005322{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005323 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005324 ssize_t index;
5325 if (patchHandle) {
5326 index = mAudioPatches.indexOfKey(*patchHandle);
5327 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005328 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 }
5330 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005331 return INVALID_OPERATION;
5332 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5334 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005335 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005336 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 removeAudioPatch(patchDesc->mHandle);
5338 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005339 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005340 return status;
5341}
5342
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005343sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005344 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005345 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005346 audio_format_t& format,
5347 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005348 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005349{
5350 // Choose an input profile based on the requested capture parameters: select the first available
5351 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005352 //
5353 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5354 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005355
Glenn Kasten730b9262018-03-29 15:01:26 -07005356 sp<IOProfile> firstInexact;
5357 uint32_t updatedSamplingRate = 0;
5358 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5359 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005360 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005361 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005362 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005363 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005364 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005365 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005366 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005367 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005368 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005369 &channelMask /*updatedChannelMask*/,
5370 // FIXME ugly cast
5371 (audio_output_flags_t) flags,
5372 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005373 return profile;
5374 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005375 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5376 samplingRate,
5377 &updatedSamplingRate,
5378 format,
5379 &updatedFormat,
5380 channelMask,
5381 &updatedChannelMask,
5382 // FIXME ugly cast
5383 (audio_output_flags_t) flags,
5384 false /*exactMatchRequiredForInputFlags*/)) {
5385 firstInexact = profile;
5386 }
5387
Eric Laurente552edb2014-03-10 17:42:56 -07005388 }
5389 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005390 if (firstInexact != nullptr) {
5391 samplingRate = updatedSamplingRate;
5392 format = updatedFormat;
5393 channelMask = updatedChannelMask;
5394 return firstInexact;
5395 }
Eric Laurente552edb2014-03-10 17:42:56 -07005396 return NULL;
5397}
5398
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005399
5400audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005401 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005402{
Eric Laurent97ac8712018-07-27 18:59:02 -07005403 // Honor explicit routing requests only if all active clients have a preferred route in which
5404 // case the last active client route is used
5405 sp<DeviceDescriptor> deviceDesc =
5406 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5407 if (deviceDesc != nullptr) {
5408 return deviceDesc->type();
5409 }
5410
5411
François Gaffie036e1e92015-03-19 10:16:24 +01005412 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5413 audio_devices_t selectedDeviceFromMix =
5414 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005415
François Gaffie036e1e92015-03-19 10:16:24 +01005416 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5417 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005418 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005419 return getDeviceForInputSource(inputSource);
5420}
5421
5422audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5423{
Eric Laurent97ac8712018-07-27 18:59:02 -07005424 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005425}
5426
Eric Laurente0720872014-03-11 09:30:41 -07005427float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005428 int index,
5429 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005430{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005431 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005432
5433 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5434 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5435 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5436 // the ringtone volume
5437 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5438 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5439 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5440 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5441 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5442 }
5443
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005444 // in-call: always cap volume by voice volume + some low headroom
5445 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005446 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005447 switch (stream) {
5448 case AUDIO_STREAM_SYSTEM:
5449 case AUDIO_STREAM_RING:
5450 case AUDIO_STREAM_MUSIC:
5451 case AUDIO_STREAM_ALARM:
5452 case AUDIO_STREAM_NOTIFICATION:
5453 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5454 case AUDIO_STREAM_DTMF:
5455 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005456 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005457 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005458 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005459 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005460 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005461 if (volumeDB > maxVoiceVolDb) {
5462 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5463 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5464 volumeDB = maxVoiceVolDb;
5465 }
5466 } break;
5467 default:
5468 break;
5469 }
5470 }
5471
Eric Laurente552edb2014-03-10 17:42:56 -07005472 // if a headset is connected, apply the following rules to ring tones and notifications
5473 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005474 // - always attenuate notifications volume by 6dB
5475 // - attenuate ring tones volume by 6dB unless music is not playing and
5476 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005477 // - if music is playing, always limit the volume to current music volume,
5478 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005479 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005480 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5481 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5482 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005483 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005484 AUDIO_DEVICE_OUT_USB_HEADSET |
5485 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005486 ((stream_strategy == STRATEGY_SONIFICATION)
5487 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005488 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005489 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005490 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005491 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005492 // when the phone is ringing we must consider that music could have been paused just before
5493 // by the music application and behave as if music was active if the last music track was
5494 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005495 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005496 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005497 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005498 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005499 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005500 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5501 musicDevice),
5502 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005503 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5504 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005505 if (volumeDB > minVolDB) {
5506 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005507 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005508 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005509 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5510 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5511 // on A2DP, also ensure notification volume is not too low compared to media when
5512 // intended to be played
5513 if ((volumeDB > -96.0f) &&
5514 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5515 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5516 stream, device,
5517 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5518 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5519 }
5520 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005521 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5522 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005523 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005524 }
5525 }
5526
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005527 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005528}
5529
Eric Laurent3839bc02018-07-10 18:33:34 -07005530int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5531 audio_stream_type_t srcStream,
5532 audio_stream_type_t dstStream)
5533{
5534 if (srcStream == dstStream) {
5535 return srcIndex;
5536 }
5537 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5538 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5539 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5540 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5541
5542 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5543}
5544
Eric Laurente0720872014-03-11 09:30:41 -07005545status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005546 int index,
5547 const sp<AudioOutputDescriptor>& outputDesc,
5548 audio_devices_t device,
5549 int delayMs,
5550 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005551{
Eric Laurente552edb2014-03-10 17:42:56 -07005552 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005554 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005555 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005556 return NO_ERROR;
5557 }
François Gaffie2110e042015-03-24 08:41:51 +01005558 audio_policy_forced_cfg_t forceUseForComm =
5559 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005560 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005561 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5562 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005563 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005564 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 return INVALID_OPERATION;
5566 }
5567
Eric Laurentc75307b2015-03-17 15:29:32 -07005568 if (device == AUDIO_DEVICE_NONE) {
5569 device = outputDesc->device();
5570 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005571
Eric Laurentffbc80f2015-03-18 18:30:19 -07005572 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005573 if (outputDesc->isFixedVolume(device) ||
5574 // Force VoIP volume to max for bluetooth SCO
5575 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5576 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005577 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005578 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005579
Eric Laurentffbc80f2015-03-18 18:30:19 -07005580 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005581
Eric Laurent3b73df72014-03-11 09:06:29 -07005582 if (stream == AUDIO_STREAM_VOICE_CALL ||
5583 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005584 float voiceVolume;
5585 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005586 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005587 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005588 } else {
5589 voiceVolume = 1.0;
5590 }
5591
Eric Laurent18fba842016-03-31 14:41:26 -07005592 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005593 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5594 mLastVoiceVolume = voiceVolume;
5595 }
5596 }
5597
5598 return NO_ERROR;
5599}
5600
Eric Laurentc75307b2015-03-17 15:29:32 -07005601void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5602 audio_devices_t device,
5603 int delayMs,
5604 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
Eric Laurentc75307b2015-03-17 15:29:32 -07005606 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005607
Eric Laurent794fde22016-03-11 09:50:45 -08005608 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005609 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005610 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005612 device,
5613 delayMs,
5614 force);
5615 }
5616}
5617
Eric Laurente0720872014-03-11 09:30:41 -07005618void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005619 bool on,
5620 const sp<AudioOutputDescriptor>& outputDesc,
5621 int delayMs,
5622 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005623{
Eric Laurent72249d52015-06-08 11:12:15 -07005624 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5625 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005626 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005627 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005629 }
5630 }
5631}
5632
Eric Laurente0720872014-03-11 09:30:41 -07005633void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005634 bool on,
5635 const sp<AudioOutputDescriptor>& outputDesc,
5636 int delayMs,
5637 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005638{
Eric Laurente552edb2014-03-10 17:42:56 -07005639 if (device == AUDIO_DEVICE_NONE) {
5640 device = outputDesc->device();
5641 }
5642
Eric Laurentc75307b2015-03-17 15:29:32 -07005643 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5644 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005645
5646 if (on) {
5647 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005648 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005649 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005650 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005651 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005652 }
5653 }
5654 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5655 outputDesc->mMuteCount[stream]++;
5656 } else {
5657 if (outputDesc->mMuteCount[stream] == 0) {
5658 ALOGV("setStreamMute() unmuting non muted stream!");
5659 return;
5660 }
5661 if (--outputDesc->mMuteCount[stream] == 0) {
5662 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005663 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005664 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005665 device,
5666 delayMs);
5667 }
5668 }
5669}
5670
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005671audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5672{
5673 // flags to stream type mapping
5674 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5675 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5676 }
5677 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5678 return AUDIO_STREAM_BLUETOOTH_SCO;
5679 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005680 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5681 return AUDIO_STREAM_TTS;
5682 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005683
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005684 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005685}
Eric Laurente83b55d2014-11-14 10:06:21 -08005686
François Gaffie53615e22015-03-19 09:24:12 +01005687bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5688{
Eric Laurente83b55d2014-11-14 10:06:21 -08005689 // has flags that map to a strategy?
5690 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5691 return true;
5692 }
5693
5694 // has known usage?
5695 switch (paa->usage) {
5696 case AUDIO_USAGE_UNKNOWN:
5697 case AUDIO_USAGE_MEDIA:
5698 case AUDIO_USAGE_VOICE_COMMUNICATION:
5699 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5700 case AUDIO_USAGE_ALARM:
5701 case AUDIO_USAGE_NOTIFICATION:
5702 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5703 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5704 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5705 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5706 case AUDIO_USAGE_NOTIFICATION_EVENT:
5707 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5708 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5709 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5710 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005711 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005712 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005713 break;
5714 default:
5715 return false;
5716 }
5717 return true;
5718}
5719
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005720bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005721 routing_strategy strategy, uint32_t inPastMs,
5722 nsecs_t sysTime) const
5723{
5724 if ((sysTime == 0) && (inPastMs != 0)) {
5725 sysTime = systemTime();
5726 }
Eric Laurent794fde22016-03-11 09:50:45 -08005727 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005728 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005729 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005730 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5731 return true;
5732 }
5733 }
5734 return false;
5735}
5736
Eric Laurent484e9272018-06-07 17:29:23 -07005737bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5738 routing_strategy strategy, uint32_t inPastMs,
5739 nsecs_t sysTime) const
5740{
5741 for (size_t i = 0; i < mOutputs.size(); i++) {
5742 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5743 if (outputDesc->sharesHwModuleWith(desc)
5744 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5745 return true;
5746 }
5747 }
5748 return false;
5749}
5750
François Gaffie2110e042015-03-24 08:41:51 +01005751audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5752{
5753 return mEngine->getForceUse(usage);
5754}
5755
5756bool AudioPolicyManager::isInCall()
5757{
5758 return isStateInCall(mEngine->getPhoneState());
5759}
5760
5761bool AudioPolicyManager::isStateInCall(int state)
5762{
5763 return is_state_in_call(state);
5764}
5765
Eric Laurentd60560a2015-04-10 11:31:20 -07005766void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5767{
5768 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005769 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5770 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5771 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5772 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005773 }
5774 }
5775
5776 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5777 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5778 bool release = false;
5779 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5780 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5781 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5782 source->ext.device.type == deviceDesc->type()) {
5783 release = true;
5784 }
5785 }
5786 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5787 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5788 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5789 sink->ext.device.type == deviceDesc->type()) {
5790 release = true;
5791 }
5792 }
5793 if (release) {
5794 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5795 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5796 }
5797 }
5798}
5799
Phil Burk09bc4612016-02-24 15:58:15 -08005800// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005801void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5802 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005803 // TODO Set this based on Config properties.
5804 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005805
5806 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5807 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005808 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005809
jiabin81772902018-04-02 17:52:27 -07005810 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5811 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5812 formats.clear();
5813 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5814 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005815 }
jiabin81772902018-04-02 17:52:27 -07005816 // Always enable IEC61937 when in MANUAL mode.
5817 formats.add(AUDIO_FORMAT_IEC61937);
5818 } else { // NEVER, AUTO or ALWAYS
5819 // Analyze original support for various formats.
5820 bool supportsAC3 = false;
5821 bool supportsOtherSurround = false;
5822 bool supportsIEC61937 = false;
5823 mSurroundFormats.clear();
5824 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5825 audio_format_t format = formats[formatIndex];
5826 switch (format) {
5827 case AUDIO_FORMAT_AC3:
5828 supportsAC3 = true;
5829 break;
5830 case AUDIO_FORMAT_E_AC3:
5831 case AUDIO_FORMAT_DTS:
5832 case AUDIO_FORMAT_DTS_HD:
5833 // If ALWAYS, remove all other surround formats here
5834 // since we will add them later.
5835 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5836 formats.removeAt(formatIndex);
5837 formatIndex--;
5838 }
5839 supportsOtherSurround = true;
5840 break;
5841 case AUDIO_FORMAT_IEC61937:
5842 supportsIEC61937 = true;
5843 break;
5844 default:
5845 break;
5846 }
5847 }
Phil Burk09bc4612016-02-24 15:58:15 -08005848
jiabin81772902018-04-02 17:52:27 -07005849 // Modify formats based on surround preferences.
5850 // If NEVER, remove support for surround formats.
5851 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5852 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5853 // Remove surround sound related formats.
5854 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5855 audio_format_t format = formats[formatIndex];
5856 switch(format) {
5857 case AUDIO_FORMAT_AC3:
5858 case AUDIO_FORMAT_E_AC3:
5859 case AUDIO_FORMAT_DTS:
5860 case AUDIO_FORMAT_DTS_HD:
5861 case AUDIO_FORMAT_IEC61937:
5862 formats.removeAt(formatIndex);
5863 break;
5864 default:
5865 formatIndex++; // keep it
5866 break;
5867 }
5868 }
5869 supportsAC3 = false;
5870 supportsOtherSurround = false;
5871 supportsIEC61937 = false;
5872 }
5873 } else { // AUTO or ALWAYS
5874 // Most TVs support AC3 even if they do not report it in the EDID.
5875 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5876 && !supportsAC3) {
5877 formats.add(AUDIO_FORMAT_AC3);
5878 supportsAC3 = true;
5879 }
5880
5881 // If ALWAYS, add support for raw surround formats if all are missing.
5882 // This assumes that if any of these formats are reported by the HAL
5883 // then the report is valid and should not be modified.
5884 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5885 formats.add(AUDIO_FORMAT_E_AC3);
5886 formats.add(AUDIO_FORMAT_DTS);
5887 formats.add(AUDIO_FORMAT_DTS_HD);
5888 supportsOtherSurround = true;
5889 }
5890
5891 // Add support for IEC61937 if any raw surround supported.
5892 // The HAL could do this but add it here, just in case.
5893 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5894 formats.add(AUDIO_FORMAT_IEC61937);
5895 supportsIEC61937 = true;
5896 }
5897
5898 // Add reported surround sound formats to enabled surround formats.
5899 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005900 audio_format_t format = formats[formatIndex];
5901 switch(format) {
5902 case AUDIO_FORMAT_AC3:
5903 case AUDIO_FORMAT_E_AC3:
5904 case AUDIO_FORMAT_DTS:
5905 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005906 case AUDIO_FORMAT_AAC_LC:
5907 case AUDIO_FORMAT_DOLBY_TRUEHD:
5908 case AUDIO_FORMAT_E_AC3_JOC:
5909 mSurroundFormats.insert(format);
Andy Hung320fd852018-10-09 14:06:37 -07005910 break;
Phil Burk07ac1142016-03-25 13:39:29 -07005911 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005912 break;
5913 }
Phil Burk09bc4612016-02-24 15:58:15 -08005914 }
Phil Burk07ac1142016-03-25 13:39:29 -07005915 }
Phil Burk09bc4612016-02-24 15:58:15 -08005916 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005917}
5918
5919// Modify the list of channel masks supported.
5920void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5921 ChannelsVector &channelMasks = *channelMasksPtr;
5922 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5923 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5924
5925 // If NEVER, then remove support for channelMasks > stereo.
5926 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5927 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5928 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5929 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5930 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5931 channelMasks.removeAt(maskIndex);
5932 } else {
5933 maskIndex++;
5934 }
5935 }
jiabin81772902018-04-02 17:52:27 -07005936 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5937 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5938 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005939 bool supports5dot1 = false;
5940 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005941 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005942 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5943 supports5dot1 = true;
5944 break;
5945 }
5946 }
5947 // If not then add 5.1 support.
5948 if (!supports5dot1) {
5949 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5950 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5951 }
Phil Burk09bc4612016-02-24 15:58:15 -08005952 }
5953}
5954
Phil Burk00eeb322016-03-31 12:41:00 -07005955void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5956 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005957 AudioProfileVector &profiles)
5958{
5959 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005960
François Gaffie112b0af2015-11-19 16:13:25 +01005961 // Format MUST be checked first to update the list of AudioProfile
5962 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005963 reply = mpClientInterface->getParameters(
5964 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005965 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005966 AudioParameter repliedParameters(reply);
5967 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005968 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005969 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5970 return;
5971 }
Phil Burk09bc4612016-02-24 15:58:15 -08005972 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005973 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005974 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005975 }
Phil Burk09bc4612016-02-24 15:58:15 -08005976 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005977 }
François Gaffie112b0af2015-11-19 16:13:25 +01005978
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005979 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005980 ChannelsVector channelMasks;
5981 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005982 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005983 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005984
5985 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005986 reply = mpClientInterface->getParameters(
5987 ioHandle,
5988 requestedParameters.toString() + ";" +
5989 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005990 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005991 AudioParameter repliedParameters(reply);
5992 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005993 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005994 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005995 }
5996 }
5997 if (profiles.hasDynamicChannelsFor(format)) {
5998 reply = mpClientInterface->getParameters(ioHandle,
5999 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006000 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006001 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006002 AudioParameter repliedParameters(reply);
6003 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006004 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006005 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006006 if (device == AUDIO_DEVICE_OUT_HDMI) {
6007 filterSurroundChannelMasks(&channelMasks);
6008 }
François Gaffie112b0af2015-11-19 16:13:25 +01006009 }
6010 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006011 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006012 }
6013}
Eric Laurentd60560a2015-04-10 11:31:20 -07006014
Mikhail Naganovdc769682018-05-04 15:34:08 -07006015status_t AudioPolicyManager::installPatch(const char *caller,
6016 audio_patch_handle_t *patchHandle,
6017 AudioIODescriptorInterface *ioDescriptor,
6018 const struct audio_patch *patch,
6019 int delayMs)
6020{
6021 ssize_t index = mAudioPatches.indexOfKey(
6022 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6023 *patchHandle : ioDescriptor->getPatchHandle());
6024 sp<AudioPatch> patchDesc;
6025 status_t status = installPatch(
6026 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6027 if (status == NO_ERROR) {
6028 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6029 }
6030 return status;
6031}
6032
6033status_t AudioPolicyManager::installPatch(const char *caller,
6034 ssize_t index,
6035 audio_patch_handle_t *patchHandle,
6036 const struct audio_patch *patch,
6037 int delayMs,
6038 uid_t uid,
6039 sp<AudioPatch> *patchDescPtr)
6040{
6041 sp<AudioPatch> patchDesc;
6042 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6043 if (index >= 0) {
6044 patchDesc = mAudioPatches.valueAt(index);
6045 afPatchHandle = patchDesc->mAfPatchHandle;
6046 }
6047
6048 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6049 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6050 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6051 if (status == NO_ERROR) {
6052 if (index < 0) {
6053 patchDesc = new AudioPatch(patch, uid);
6054 addAudioPatch(patchDesc->mHandle, patchDesc);
6055 } else {
6056 patchDesc->mPatch = *patch;
6057 }
6058 patchDesc->mAfPatchHandle = afPatchHandle;
6059 if (patchHandle) {
6060 *patchHandle = patchDesc->mHandle;
6061 }
6062 nextAudioPortGeneration();
6063 mpClientInterface->onAudioPatchListUpdate();
6064 }
6065 if (patchDescPtr) *patchDescPtr = patchDesc;
6066 return status;
6067}
6068
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006069} // namespace android