blob: 6fe7fc11167b05dcf04c5fb822e0cf6f5341c8fb [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.
Nadav Bar20919492018-11-20 10:20:51 +0200843 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300844 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200845 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300846 audio_is_linear_pcm(config->format) &&
847 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700848 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300849 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
850 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700851 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300852 device = mEngine->getDeviceForStrategy(strategy);
853 }
854 }
855
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800856 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
857 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200858 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100860 *output = AUDIO_IO_HANDLE_NONE;
861 if (msdDevice != AUDIO_DEVICE_NONE) {
862 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
863 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
864 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
865 __func__, msdDevice, device);
866 device = msdDevice;
867 } else {
868 *output = AUDIO_IO_HANDLE_NONE;
869 }
870 }
871 if (*output == AUDIO_IO_HANDLE_NONE) {
872 *output = getOutputForDevice(device, session, *stream, config, flags);
873 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800874 if (*output == AUDIO_IO_HANDLE_NONE) {
875 return INVALID_OPERATION;
876 }
Paul McLeanaa981192015-03-21 09:55:15 -0700877
Eric Laurent8fc147b2018-07-22 19:13:55 -0700878 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700879 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
880 : AUDIO_PORT_HANDLE_NONE;
881
Eric Laurent8fc147b2018-07-22 19:13:55 -0700882exit:
883 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
884 .format = config->format,
885 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700886 *portId = AudioPort::getNextUniqueId();
887
Eric Laurent8fc147b2018-07-22 19:13:55 -0700888 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700889 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
890 requestedDeviceId, *stream,
891 getStrategyForAttr(&attributes),
892 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700893 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700894 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700895
896 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
897 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700898
Eric Laurente83b55d2014-11-14 10:06:21 -0800899 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700900}
901
902audio_io_handle_t AudioPolicyManager::getOutputForDevice(
903 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800904 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700905 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800906 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200907 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700908{
Andy Hungc88b0642018-04-27 15:42:35 -0700909 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700910 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700911
Eric Laurente552edb2014-03-10 17:42:56 -0700912 // open a direct output if required by specified parameters
913 //force direct flag if offload flag is set: offloading implies a direct output stream
914 // and all common behaviors are driven by checking only the direct flag
915 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200916 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
917 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 }
Nadav Bar766fb022018-01-07 12:18:03 +0200919 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
920 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700921 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800922 // only allow deep buffering for music stream type
923 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200924 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700925 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200926 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700927 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
928 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200929 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800930 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700931 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200932 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700933 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200934 audio_is_linear_pcm(config->format) &&
935 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200936 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700937 AUDIO_OUTPUT_FLAG_DIRECT);
938 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700939 }
Eric Laurente552edb2014-03-10 17:42:56 -0700940
Nadav Bar766fb022018-01-07 12:18:03 +0200941
Eric Laurentb732cf52014-09-24 19:08:21 -0700942 sp<IOProfile> profile;
943
944 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700945 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200946 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800947 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
948 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700949 goto non_direct_output;
950 }
951
Andy Hung2ddee192015-12-18 17:34:44 -0800952 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
953 // This prevents creating an offloaded track and tearing it down immediately after start
954 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700955 // FIXME: We should check the audio session here but we do not have it in this context.
956 // This may prevent offloading in rare situations where effects are left active by apps
957 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700958
Nadav Bar766fb022018-01-07 12:18:03 +0200959 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800960 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700961 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800962 config->sample_rate,
963 config->format,
964 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200965 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700966 }
967
Eric Laurent1c333e22014-05-20 10:48:17 -0700968 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700969 // exclusive outputs for MMAP and Offload are enforced by different session ids.
970 for (size_t i = 0; i < mOutputs.size(); i++) {
971 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
972 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
973 // reuse direct output if currently open by the same client
974 // and configured with same parameters
975 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700976 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700977 (config->channel_mask == desc->mChannelMask) &&
978 (session == desc->mDirectClientSession)) {
979 desc->mDirectOpenCount++;
980 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
981 mOutputs.keyAt(i), session);
982 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700983 }
984 }
985 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800986
987 if (!profile->canOpenNewIo()) {
988 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
Eric Laurent861a6282015-05-18 15:40:16 -0700990
Eric Laurent3974e3b2017-12-07 17:58:43 -0800991 sp<SwAudioOutputDescriptor> outputDesc =
992 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800993
Mikhail Naganov708e0382018-05-30 09:53:04 -0700994 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800995 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
996 : String8("");
997
Dean Wheatley3023b382018-08-09 07:42:40 +1000998 // MSD patch may be using the only output stream that can service this request. Release
999 // MSD patch to prioritize this request over any active output on MSD.
1000 AudioPatchCollection msdPatches = getMsdPatches();
1001 for (size_t i = 0; i < msdPatches.size(); i++) {
1002 const auto& patch = msdPatches[i];
1003 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1004 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1005 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1006 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1007 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1008 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1009 releaseAudioPatch(patch->mHandle, mUidCached);
1010 break;
1011 }
1012 }
1013 }
1014
Nadav Bar766fb022018-01-07 12:18:03 +02001015 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001016
1017 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001018 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001019 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001020 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001021 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1022 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1023 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1024 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1025 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001026 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001027 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001028 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001029 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001030 if (audio_is_linear_pcm(config->format) &&
1031 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001032 goto non_direct_output;
1033 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001034 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001035 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001036 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001037 outputDesc->mDirectClientSession = session;
1038
Eric Laurente552edb2014-03-10 17:42:56 -07001039 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001040 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001041 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001042 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001043 return output;
1044 }
1045
Eric Laurentb732cf52014-09-24 19:08:21 -07001046non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001047
1048 // A request for HW A/V sync cannot fallback to a mixed output because time
1049 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001050 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001051 return AUDIO_IO_HANDLE_NONE;
1052 }
1053
Eric Laurente552edb2014-03-10 17:42:56 -07001054 // ignoring channel mask due to downmix capability in mixer
1055
1056 // open a non direct output
1057
1058 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001059 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001060 // get which output is suitable for the specified stream. The actual
1061 // routing change will happen when startOutput() will be called
1062 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1063
Eric Laurent8838a382014-09-08 16:44:28 -07001064 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001065 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1066 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001067 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001068 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001069 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001070 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001071
Eric Laurente552edb2014-03-10 17:42:56 -07001072 return output;
1073}
1074
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001075sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001076 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001077 if (msdModule != 0) {
1078 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1079 msdModule->getHandle());
1080 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1081 }
1082 return 0;
1083}
1084
1085audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001086 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001087 if (msdModule != 0) {
1088 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1089 }
1090 return AUDIO_DEVICE_NONE;
1091}
1092
1093const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1094 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001095 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1096 if (msdModule != 0) {
1097 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1098 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1099 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1100 const struct audio_port_config *source = &patch->mPatch.sources[j];
1101 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1102 source->ext.device.hw_module == msdModule->getHandle()) {
1103 msdPatches.addAudioPatch(patch->mHandle, patch);
1104 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001105 }
1106 }
1107 }
1108 return msdPatches;
1109}
1110
1111status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1112 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1113{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001114 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001115 if (msdModule == nullptr) {
1116 ALOGE("%s() unable to get MSD module", __func__);
1117 return NO_INIT;
1118 }
1119 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1120 if (deviceModule == nullptr) {
1121 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1122 return NO_INIT;
1123 }
1124 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1125 if (inputProfiles.isEmpty()) {
1126 ALOGE("%s() no input profiles for MSD module", __func__);
1127 return NO_INIT;
1128 }
1129 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1130 if (outputProfiles.isEmpty()) {
1131 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1132 return NO_INIT;
1133 }
1134 AudioProfileVector msdProfiles;
1135 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1136 for (const auto &inProfile : inputProfiles) {
1137 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1138 msdProfiles.appendVector(inProfile->getAudioProfiles());
1139 }
1140 }
1141 AudioProfileVector deviceProfiles;
1142 for (const auto &outProfile : outputProfiles) {
1143 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1144 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1145 }
1146 }
1147 struct audio_config_base bestSinkConfig;
1148 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1149 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1150 &bestSinkConfig);
1151 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001152 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1153 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001154 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001155 }
1156 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1157 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1158 sinkConfig->format = bestSinkConfig.format;
1159 // For encoded streams force direct flag to prevent downstream mixing.
1160 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1161 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1162 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1163 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1164 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1165 sourceConfig->format = bestSinkConfig.format;
1166 // Copy input stream directly without any processing (e.g. resampling).
1167 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1168 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1169 if (hwAvSync) {
1170 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1171 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1172 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1173 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1174 }
1175 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1176 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1177 sinkConfig->config_mask |= config_mask;
1178 sourceConfig->config_mask |= config_mask;
1179 return NO_ERROR;
1180}
1181
1182PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1183{
1184 PatchBuilder patchBuilder;
1185 patchBuilder.addSource(getMsdAudioInDevice()).
1186 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1187 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1188 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1189 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1190 // For now, we just forcefully try with HwAvSync first.
1191 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1192 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1193 getBestMsdAudioProfileFor(
1194 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1195 if (res == NO_ERROR) {
1196 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1197 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1198 }
1199 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1200 " supporting PCM format conversion.", __func__);
1201 return patchBuilder;
1202}
1203
1204status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1205 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1206 if (outputDevice == AUDIO_DEVICE_NONE) {
1207 // Use media strategy for unspecified output device. This should only
1208 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1209 // therefore invalidate explicit routing requests.
1210 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1211 }
1212 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1213 const struct audio_patch* patch = patchBuilder.patch();
1214 const AudioPatchCollection msdPatches = getMsdPatches();
1215 if (!msdPatches.isEmpty()) {
1216 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1217 "The current MSD prototype only supports one output patch");
1218 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1219 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1220 return NO_ERROR;
1221 }
1222 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1223 }
1224 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1225 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1226 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1227 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1228 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1229 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1230 return status;
1231}
1232
Eric Laurente0720872014-03-11 09:30:41 -07001233audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001234 audio_output_flags_t flags,
1235 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001236{
1237 // select one output among several that provide a path to a particular device or set of
1238 // devices (the list was previously build by getOutputsForDevice()).
1239 // The priority is as follows:
1240 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001241 // 2: the output with the bit depth the closest to the requested one
1242 // 3: the primary output
1243 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001244
1245 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001246 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001247 }
1248 if (outputs.size() == 1) {
1249 return outputs[0];
1250 }
1251
1252 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001253 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1254 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1255 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001256 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1257 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001258
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001259 for (audio_io_handle_t output : outputs) {
1260 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001261 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001262 // if a valid format is specified, skip output if not compatible
1263 if (format != AUDIO_FORMAT_INVALID) {
1264 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001265 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001266 continue;
1267 }
1268 } else if (!audio_is_linear_pcm(format)) {
1269 continue;
1270 }
Eric Laurente6930022016-02-11 10:20:40 -08001271 if (AudioPort::isBetterFormatMatch(
1272 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001273 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001274 bestFormat = outputDesc->mFormat;
1275 }
Eric Laurent8838a382014-09-08 16:44:28 -07001276 }
1277
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001278 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001279 if (commonFlags >= maxCommonFlags) {
1280 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001281 if (format != AUDIO_FORMAT_INVALID
1282 && AudioPort::isBetterFormatMatch(
1283 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001284 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001285 bestFormatForFlags = outputDesc->mFormat;
1286 }
1287 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001288 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001289 maxCommonFlags = commonFlags;
1290 bestFormatForFlags = outputDesc->mFormat;
1291 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001292 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001293 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001294 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001295 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
1297 }
1298 }
1299
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001300 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001301 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001304 return outputForFormat;
1305 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
1309
1310 return outputs[0];
1311}
1312
Eric Laurent8fc147b2018-07-22 19:13:55 -07001313status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001314{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001315 ALOGV("%s portId %d", __FUNCTION__, portId);
1316
1317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1318 if (outputDesc == 0) {
1319 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 return BAD_VALUE;
1321 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001322 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001323
Eric Laurent8fc147b2018-07-22 19:13:55 -07001324 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001325 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001326
Eric Laurent733ce942017-12-07 12:18:25 -08001327 status_t status = outputDesc->start();
1328 if (status != NO_ERROR) {
1329 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001330 }
1331
Eric Laurent97ac8712018-07-27 18:59:02 -07001332 uint32_t delayMs;
1333 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
1335 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001336 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001337 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (delayMs != 0) {
1340 usleep(delayMs * 1000);
1341 }
1342
1343 return status;
1344}
1345
Eric Laurent97ac8712018-07-27 18:59:02 -07001346status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1347 const sp<TrackClientDescriptor>& client,
1348 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001349{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001350 // cannot start playback of STREAM_TTS if any other output is being used
1351 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001352
1353 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001354 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001355 if (stream == AUDIO_STREAM_TTS) {
1356 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001357 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001358 return INVALID_OPERATION;
1359 } else {
1360 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1361 }
1362 } else {
1363 // some playback other than beacon starts
1364 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1365 }
1366
Eric Laurent77305a62016-07-25 16:39:22 -07001367 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001368 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001369 bool force = !outputDesc->isActive() &&
1370 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001371
Eric Laurent97ac8712018-07-27 18:59:02 -07001372 audio_devices_t device = AUDIO_DEVICE_NONE;
1373 AudioMix *policyMix = NULL;
1374 const char *address = NULL;
1375 if (outputDesc->mPolicyMix != NULL) {
1376 policyMix = outputDesc->mPolicyMix;
1377 address = policyMix->mDeviceAddress.string();
1378 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1379 device = policyMix->mDeviceType;
1380 } else {
1381 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1382 }
1383 }
1384
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001385 // requiresMuteCheck is false when we can bypass mute strategy.
1386 // It covers a common case when there is no materially active audio
1387 // and muting would result in unnecessary delay and dropped audio.
1388 const uint32_t outputLatencyMs = outputDesc->latency();
1389 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1390
Eric Laurente552edb2014-03-10 17:42:56 -07001391 // increment usage count for this stream on the requested output:
1392 // NOTE that the usage count is the same for duplicated output and hardware output which is
1393 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001394 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001395
1396 if (client->hasPreferredDevice(true)) {
1397 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1398 if (device != outputDesc->device()) {
1399 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1400 }
1401 }
Eric Laurente552edb2014-03-10 17:42:56 -07001402
Eric Laurent36829f92017-04-07 19:04:42 -07001403 if (stream == AUDIO_STREAM_MUSIC) {
1404 selectOutputForMusicEffects();
1405 }
1406
Eric Laurent592dd7b2018-08-05 18:58:48 -07001407 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001408 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 if (device == AUDIO_DEVICE_NONE) {
1410 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001411 }
Eric Laurent36829f92017-04-07 19:04:42 -07001412
Eric Laurente552edb2014-03-10 17:42:56 -07001413 routing_strategy strategy = getStrategy(stream);
1414 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001415 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1416 (beaconMuteLatency > 0);
1417 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001418 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001420 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001421 // An output has a shared device if
1422 // - managed by the same hw module
1423 // - supports the currently selected device
1424 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1425 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1426
Eric Laurent77305a62016-07-25 16:39:22 -07001427 // force a device change if any other output is:
1428 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001429 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001430 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001431 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001432 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001433 // change the device currently selected by the other output.
1434 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001435 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001437 force = true;
1438 }
1439 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001440 // a notification so that audio focus effect can propagate, or that a mute/unmute
1441 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001442 const uint32_t latencyMs = desc->latency();
1443 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1444
1445 if (shouldWait && isActive && (waitMs < latencyMs)) {
1446 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001447 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001448
1449 // Require mute check if another output is on a shared device
1450 // and currently active to have proper drain and avoid pops.
1451 // Note restoring AudioTracks onto this output needs to invoke
1452 // a volume ramp if there is no mute.
1453 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001454 }
1455 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001456
1457 const uint32_t muteWaitMs =
1458 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001459
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // apply volume rules for current stream and device if necessary
1461 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001462 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001463 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001464 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001465
1466 // update the outputs if starting an output with a stream that can affect notification
1467 // routing
1468 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001469
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001470 // force reevaluating accessibility routing when ringtone or alarm starts
1471 if (strategy == STRATEGY_SONIFICATION) {
1472 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1473 }
Eric Laurentdc462862016-07-19 12:29:53 -07001474
1475 if (waitMs > muteWaitMs) {
1476 *delayMs = waitMs - muteWaitMs;
1477 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001478
1479 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1480 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1481 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1482 // change occurs after the MixerThread starts and causes a stream volume
1483 // glitch.
1484 //
1485 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
Eric Laurentdc462862016-07-19 12:29:53 -07001487
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001488 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1489 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1490 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1491 }
1492
Eric Laurent97ac8712018-07-27 18:59:02 -07001493 // Automatically enable the remote submix input when output is started on a re routing mix
1494 // of type MIX_TYPE_RECORDERS
1495 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1496 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1499 address,
1500 "remote-submix");
1501 }
1502
Eric Laurente552edb2014-03-10 17:42:56 -07001503 return NO_ERROR;
1504}
1505
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508 ALOGV("%s portId %d", __FUNCTION__, portId);
1509
1510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1511 if (outputDesc == 0) {
1512 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 return BAD_VALUE;
1514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001515 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 ALOGV("stopOutput() output %d, stream %d, session %d",
1518 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001519
Eric Laurent97ac8712018-07-27 18:59:02 -07001520 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001521
Eric Laurent733ce942017-12-07 12:18:25 -08001522 if (status == NO_ERROR ) {
1523 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001524 }
1525 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001526}
1527
Eric Laurent97ac8712018-07-27 18:59:02 -07001528status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1529 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001530{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001531 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001532 audio_stream_type_t stream = client->stream();
1533
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001534 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1535
Eric Laurent592dd7b2018-08-05 18:58:48 -07001536 if (outputDesc->streamActiveCount(stream) > 0) {
1537 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001538 // Automatically disable the remote submix input when output is stopped on a
1539 // re routing mix of type MIX_TYPE_RECORDERS
1540 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1541 outputDesc->mPolicyMix != NULL &&
1542 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1543 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1544 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1545 outputDesc->mPolicyMix->mDeviceAddress,
1546 "remote-submix");
1547 }
1548 }
1549 bool forceDeviceUpdate = false;
1550 if (client->hasPreferredDevice(true)) {
1551 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1552 forceDeviceUpdate = true;
1553 }
1554
Eric Laurente552edb2014-03-10 17:42:56 -07001555 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001556 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001557
Eric Laurente552edb2014-03-10 17:42:56 -07001558 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001559 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001560 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001561 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001562 // delay the device switch by twice the latency because stopOutput() is executed when
1563 // the track stop() command is received and at that time the audio track buffer can
1564 // still contain data that needs to be drained. The latency only covers the audio HAL
1565 // and kernel buffers. Also the latency does not always include additional delay in the
1566 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001567 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001568
1569 // force restoring the device selection on other active outputs if it differs from the
1570 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001571 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001572 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001573 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001575 desc->isActive() &&
1576 outputDesc->sharesHwModuleWith(desc) &&
1577 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001578 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1579 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001580
Eric Laurentc75307b2015-03-17 15:29:32 -07001581 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001582 newDevice2,
1583 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001584 delayMs);
1585 // re-apply device specific volume if not done by setOutputDevice()
1586 if (!force) {
1587 applyStreamVolumes(desc, newDevice2, delayMs);
1588 }
Eric Laurente552edb2014-03-10 17:42:56 -07001589 }
1590 }
1591 // update the outputs if stopping one with a stream that can affect notification routing
1592 handleNotificationRoutingForStream(stream);
1593 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001594
1595 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1596 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1597 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1598 }
1599
Eric Laurent36829f92017-04-07 19:04:42 -07001600 if (stream == AUDIO_STREAM_MUSIC) {
1601 selectOutputForMusicEffects();
1602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603 return NO_ERROR;
1604 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001605 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001606 return INVALID_OPERATION;
1607 }
1608}
1609
Eric Laurent8fc147b2018-07-22 19:13:55 -07001610void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001611{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001612 ALOGV("%s portId %d", __FUNCTION__, portId);
1613
1614 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1615 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001616 // If an output descriptor is closed due to a device routing change,
1617 // then there are race conditions with releaseOutput from tracks
1618 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1619 // destroyed shortly thereafter.
1620 //
1621 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001622 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 return;
1624 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001625
1626 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 return;
1633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 if (--outputDesc->mDirectOpenCount == 0) {
1635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001637 }
1638 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001639 // stopOutput() needs to be successfully called before releaseOutput()
1640 // otherwise there may be inaccurate stream reference counts.
1641 // This is checked in outputDesc->removeClient below.
1642 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001643}
1644
Eric Laurentcaf7f482014-11-25 17:50:47 -08001645status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1646 audio_io_handle_t *input,
1647 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001648 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001649 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001650 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001651 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001652 input_type_t *inputType,
1653 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001655 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001656 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001657 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurentad2e7b92017-09-14 20:06:42 -07001659 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001660 // handle legacy remote submix case where the address was not always specified
1661 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001662 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001663 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001664 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001665 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001666 sp<AudioInputDescriptor> inputDesc;
1667 sp<RecordClientDescriptor> clientDesc;
1668 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001669 bool isSoundTrigger;
1670 audio_devices_t device;
1671
1672 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1673 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1674 return INVALID_OPERATION;
1675 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001676
Eric Laurentfe231122017-11-17 17:48:06 -08001677 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1678 inputSource = AUDIO_SOURCE_MIC;
1679 }
1680
Paul McLean466dc8e2015-04-17 13:15:36 -06001681 // Explicit routing?
1682 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001683 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001684 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001685 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001686
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1688 // possible
1689 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1690 *input != AUDIO_IO_HANDLE_NONE) {
1691 ssize_t index = mInputs.indexOfKey(*input);
1692 if (index < 0) {
1693 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1694 status = BAD_VALUE;
1695 goto error;
1696 }
1697 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001698 RecordClientVector clients = inputDesc->getClientsForSession(session);
1699 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001700 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1701 status = BAD_VALUE;
1702 goto error;
1703 }
1704 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1705 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001706 // corresponds to a new client and is only permitted from the same UID.
1707 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001708 if (clients.size() > 1) {
1709 for (const auto& client : clients) {
1710 // The client map is ordered by key values (portId) and portIds are allocated
1711 // incrementaly. So the first client in this list is the one opened by audio flinger
1712 // when the mmap stream is created and should be ignored as it does not correspond
1713 // to an actual client
1714 if (client == *clients.cbegin()) {
1715 continue;
1716 }
1717 if (uid != client->uid() && !client->isSilenced()) {
1718 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1719 uid, client->portId(), client->uid());
1720 status = INVALID_OPERATION;
1721 goto error;
1722 }
Eric Laurent331679c2018-04-16 17:03:16 -07001723 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001727
Eric Laurent8f42ea12018-08-08 09:08:25 -07001728 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001729 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 }
1731
1732 *input = AUDIO_IO_HANDLE_NONE;
1733 *inputType = API_INPUT_INVALID;
1734
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 halInputSource = inputSource;
1736
Eric Laurentc447ded2015-01-06 08:47:05 -08001737 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001738 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1740 if (status != NO_ERROR) {
1741 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001742 }
1743 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1745 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 if (deviceDesc != 0) {
1748 device = deviceDesc->type();
1749 } else {
1750 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1751 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001752 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001753 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001754 status = BAD_VALUE;
1755 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001756 }
Eric Laurentc722f302014-12-10 11:21:49 -08001757 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001758 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001759 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1760 // there is an external policy, but this input is attached to a mix of recorders,
1761 // meaning it receives audio injected into the framework, so the recorder doesn't
1762 // know about it and is therefore considered "legacy"
1763 *inputType = API_INPUT_LEGACY;
1764 } else {
1765 // recording a mix of players defined by an external policy, we're rerouting for
1766 // an external policy
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1768 }
Eric Laurentc722f302014-12-10 11:21:49 -08001769 } else if (audio_is_remote_submix_device(device)) {
1770 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001771 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001772 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1773 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001774 } else {
1775 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001776 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001777
Eric Laurent599c7582015-12-07 18:05:55 -08001778 }
1779
Eric Laurent8f42ea12018-08-08 09:08:25 -07001780 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001781 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001782 policyMix);
1783 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001784 status = INVALID_OPERATION;
1785 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001786 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001787
Eric Laurent8f42ea12018-08-08 09:08:25 -07001788exit:
1789
Mikhail Naganov708e0382018-05-30 09:53:04 -07001790 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001791 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001793
Eric Laurent8f42ea12018-08-08 09:08:25 -07001794 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1795 mSoundTriggerSessions.indexOfKey(session) > 0;
1796 *portId = AudioPort::getNextUniqueId();
1797
Eric Laurent8fc147b2018-07-22 19:13:55 -07001798 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001799 *attr, *config, requestedDeviceId,
1800 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001801 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001802 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001803
1804 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1805 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001806
Eric Laurent599c7582015-12-07 18:05:55 -08001807 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808
1809error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001811}
1812
1813
1814audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1815 String8 address,
1816 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001817 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001818 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001819 audio_input_flags_t flags,
1820 AudioMix *policyMix)
1821{
1822 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1823 audio_source_t halInputSource = inputSource;
1824 bool isSoundTrigger = false;
1825
1826 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1827 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1828 if (index >= 0) {
1829 input = mSoundTriggerSessions.valueFor(session);
1830 isSoundTrigger = true;
1831 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1832 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1833 } else {
1834 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001835 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001836 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001837 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001838 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001839 }
1840
Andy Hungf129b032015-04-07 13:45:50 -07001841 // find a compatible input profile (not necessarily identical in parameters)
1842 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001843 // sampling rate and flags may be updated by getInputProfile
1844 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1845 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001846 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001847 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001848 audio_input_flags_t profileFlags = flags;
1849 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001850 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001851 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001852 profileSamplingRate, profileFormat, profileChannelMask,
1853 profileFlags);
1854 if (profile != 0) {
1855 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001856 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1857 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001858 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1859 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1860 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001861 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001862 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1863 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001864 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001865 }
Eric Laurente552edb2014-03-10 17:42:56 -07001866 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001867 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001868 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001869 if (samplingRate == 0) {
1870 samplingRate = profileSamplingRate;
1871 }
Eric Laurente552edb2014-03-10 17:42:56 -07001872
Eric Laurent322b4d22015-04-03 15:57:54 -07001873 if (profile->getModuleHandle() == 0) {
1874 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001875 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001876 }
1877
Eric Laurent3974e3b2017-12-07 17:58:43 -08001878 if (!profile->canOpenNewIo()) {
1879 return AUDIO_IO_HANDLE_NONE;
1880 }
1881
Eric Laurentfe231122017-11-17 17:48:06 -08001882 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001883
Eric Laurentfe231122017-11-17 17:48:06 -08001884 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1885 lConfig.sample_rate = profileSamplingRate;
1886 lConfig.channel_mask = profileChannelMask;
1887 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001888
Eric Laurent53b810e2017-12-10 17:25:10 -08001889 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001890 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001891 // the inputs vector must be of size >= 1, but we don't want to crash here
1892 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1893 }
1894
Eric Laurentfe231122017-11-17 17:48:06 -08001895 status_t status = inputDesc->open(&lConfig, device, address,
1896 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001897
1898 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001899 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001900 (profileSamplingRate != lConfig.sample_rate) ||
1901 !audio_formats_match(profileFormat, lConfig.format) ||
1902 (profileChannelMask != lConfig.channel_mask)) {
1903 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001904 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001905 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001906 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001907 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001908 }
Eric Laurent599c7582015-12-07 18:05:55 -08001909 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001910 }
1911
Eric Laurentc722f302014-12-10 11:21:49 -08001912 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001913
Eric Laurent599c7582015-12-07 18:05:55 -08001914 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001915 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001916
Eric Laurent599c7582015-12-07 18:05:55 -08001917 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001918}
1919
Eric Laurentbb948092017-01-23 18:33:30 -08001920//static
1921bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1922{
1923 return (source == AUDIO_SOURCE_HOTWORD) ||
1924 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1925 (source == AUDIO_SOURCE_FM_TUNER);
1926}
1927
Chris Thornton2b864642017-06-27 21:26:07 -07001928// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1929bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1930 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1931 bool soundTriggerSupportsConcurrentCapture = false;
1932 unsigned int numModules = 0;
1933 struct sound_trigger_module_descriptor* nModules = NULL;
1934
1935 status_t status = SoundTrigger::listModules(nModules, &numModules);
1936 if (status == NO_ERROR && numModules != 0) {
1937 nModules = (struct sound_trigger_module_descriptor*) calloc(
1938 numModules, sizeof(struct sound_trigger_module_descriptor));
1939 if (nModules == NULL) {
1940 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1941 // ram the next time this function is called.
1942 ALOGE("Failed to allocate buffer for module descriptors");
1943 return false;
1944 }
1945
1946 status = SoundTrigger::listModules(nModules, &numModules);
1947 if (status == NO_ERROR) {
1948 soundTriggerSupportsConcurrentCapture = true;
1949 for (size_t i = 0; i < numModules; ++i) {
1950 soundTriggerSupportsConcurrentCapture &=
1951 nModules[i].properties.concurrent_capture;
1952 }
1953 }
1954 free(nModules);
1955 }
1956 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1957 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1958 }
1959 return mSoundTriggerSupportsConcurrentCapture;
1960}
1961
Eric Laurentfb66dd92016-01-28 18:32:03 -08001962
Eric Laurent8fc147b2018-07-22 19:13:55 -07001963status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001964 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001965 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001966{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001967 *concurrency = API_INPUT_CONCURRENCY_NONE;
1968
1969 ALOGV("%s portId %d", __FUNCTION__, portId);
1970
1971 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1972 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001973 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001974 return BAD_VALUE;
1975 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001977 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001978 if (client->active()) {
1979 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1980 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001981 }
1982
Eric Laurent8f42ea12018-08-08 09:08:25 -07001983 audio_session_t session = client->session();
1984
1985 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1986 __FUNCTION__, input, session, silenced, *concurrency);
1987
Eric Laurent74708e72017-04-07 17:13:42 -07001988 if (!is_virtual_input_device(inputDesc->mDevice)) {
1989 if (mCallTxPatch != 0 &&
1990 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1991 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001992 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001993 return INVALID_OPERATION;
1994 }
1995
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001996 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001997
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001998 // If a UID is idle and records silence and another not silenced recording starts
1999 // from another UID (idle or active) we stop the current idle UID recording in
2000 // favor of the new one - "There can be only one" TM
2001 if (!silenced) {
2002 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002003 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002004 activeDesc->getId() == inputDesc->getId()) {
2005 continue;
2006 }
2007
Eric Laurent8f42ea12018-08-08 09:08:25 -07002008 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2009 for (const auto& activeClient : activeClients) {
2010 if (activeClient->isSilenced()) {
2011 closeClient(activeClient->portId());
2012 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2013 portId, activeClient->portId());
2014 activeInputs = mInputs.getActiveInputs();
2015 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002016 }
2017 }
2018 }
2019
2020 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002021 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002022 activeDesc->getId() == inputDesc->getId()) {
2023 continue;
2024 }
2025
Eric Laurent74708e72017-04-07 17:13:42 -07002026 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002027 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002028 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2029 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002030 ALOGW("%s input %d failed for HOTWORD: "
2031 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002032 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002033 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002034 return INVALID_OPERATION;
2035 }
2036 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002037 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2038 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002039 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002040 return INVALID_OPERATION;
2041 }
2042 } else {
2043 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002044 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002045 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002046 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002047 return INVALID_OPERATION;
2048 }
2049 }
2050 }
2051
Chris Thornton2b864642017-06-27 21:26:07 -07002052 // We only need to check if the sound trigger session supports concurrent capture if the
2053 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2054 // that's running.
2055 const bool allowConcurrentWithSoundTrigger =
2056 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2057
Eric Laurent74708e72017-04-07 17:13:42 -07002058 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002059 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002060 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2061 continue;
2062 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002063 RecordClientVector activeHotwordClients =
2064 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2065 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002066 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002067
2068 for (const auto& activeClient : activeHotwordClients) {
2069 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2070 sessions.add(activeClient->session());
2071 closeClient(activeClient->portId());
2072 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2073 input, activeDesc->mIoHandle);
2074 }
2075
Eric Laurent74708e72017-04-07 17:13:42 -07002076 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002077 }
2078 }
2079 }
Eric Laurente552edb2014-03-10 17:42:56 -07002080
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002081 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002082 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002083
Eric Laurent313d1e72016-01-29 09:56:57 -08002084 // increment activity count before calling getNewInputDevice() below as only active sessions
2085 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002087
Eric Laurent8f42ea12018-08-08 09:08:25 -07002088 // indicate active capture to sound trigger service if starting capture from a mic on
2089 // primary HW module
2090 audio_devices_t device = getNewInputDevice(inputDesc);
2091 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002092
Eric Laurent8f42ea12018-08-08 09:08:25 -07002093 status_t status = inputDesc->start();
2094 if (status != NO_ERROR) {
2095 inputDesc->setClientActive(client, false);
2096 return status;
2097 }
2098
2099 if (inputDesc->activeCount() == 1) {
2100 // if input maps to a dynamic policy with an activity listener, notify of state change
2101 if ((inputDesc->mPolicyMix != NULL)
2102 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2103 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2104 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002105 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002106
Eric Laurent8f42ea12018-08-08 09:08:25 -07002107 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2108 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2109 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2110 SoundTrigger::setCaptureState(true);
2111 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002112
Eric Laurent8f42ea12018-08-08 09:08:25 -07002113 // automatically enable the remote submix output when input is started if not
2114 // used by a policy mix of type MIX_TYPE_RECORDERS
2115 // For remote submix (a virtual device), we open only one input per capture request.
2116 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2117 String8 address = String8("");
2118 if (inputDesc->mPolicyMix == NULL) {
2119 address = String8("0");
2120 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2121 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002122 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002123 if (address != "") {
2124 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2125 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2126 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002127 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002128 }
Eric Laurente552edb2014-03-10 17:42:56 -07002129 }
2130
Eric Laurent8f42ea12018-08-08 09:08:25 -07002131 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002132
Eric Laurente552edb2014-03-10 17:42:56 -07002133 return NO_ERROR;
2134}
2135
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002137{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138 ALOGV("%s portId %d", __FUNCTION__, portId);
2139
2140 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2141 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002142 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002143 return BAD_VALUE;
2144 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002145 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002146 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002147 if (!client->active()) {
2148 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002149 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002150 }
2151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002153
Eric Laurent8f42ea12018-08-08 09:08:25 -07002154 inputDesc->stop();
2155 if (inputDesc->isActive()) {
2156 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2157 } else {
2158 // if input maps to a dynamic policy with an activity listener, notify of state change
2159 if ((inputDesc->mPolicyMix != NULL)
2160 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2161 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2162 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002163 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002164
2165 // automatically disable the remote submix output when input is stopped if not
2166 // used by a policy mix of type MIX_TYPE_RECORDERS
2167 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2168 String8 address = String8("");
2169 if (inputDesc->mPolicyMix == NULL) {
2170 address = String8("0");
2171 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2172 address = inputDesc->mPolicyMix->mDeviceAddress;
2173 }
2174 if (address != "") {
2175 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2177 address, "remote-submix");
2178 }
2179 }
2180
2181 audio_devices_t device = inputDesc->mDevice;
2182 resetInputDevice(input);
2183
2184 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2185 // primary HW module
2186 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2187 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2188 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2189 SoundTrigger::setCaptureState(false);
2190 }
2191 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002192 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002193 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002194}
2195
Eric Laurent8fc147b2018-07-22 19:13:55 -07002196void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002197{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002198 ALOGV("%s portId %d", __FUNCTION__, portId);
2199
2200 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2201 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002202 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002203 return;
2204 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002205 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002206 audio_io_handle_t input = inputDesc->mIoHandle;
2207
Eric Laurent8f42ea12018-08-08 09:08:25 -07002208 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002209
Andy Hung39efb7a2018-09-26 15:39:28 -07002210 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002211
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 if (inputDesc->getClientCount() > 0) {
2213 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002214 return;
2215 }
2216
Eric Laurent05b90f82014-08-27 15:32:29 -07002217 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002218 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002219 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002220}
2221
Eric Laurent8f42ea12018-08-08 09:08:25 -07002222void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002223{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002224 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002225
2226 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002227 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002228 }
2229}
2230
Eric Laurent8f42ea12018-08-08 09:08:25 -07002231void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2232{
2233 stopInput(portId);
2234 releaseInput(portId);
2235}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236
Eric Laurentd4692962014-05-05 18:13:44 -07002237void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002238 bool patchRemoved = false;
2239
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002240 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002241 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002242 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002243 if (patch_index >= 0) {
2244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002245 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002246 mAudioPatches.removeItemsAt(patch_index);
2247 patchRemoved = true;
2248 }
Eric Laurentfe231122017-11-17 17:48:06 -08002249 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002250 }
2251 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002252 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002253 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002254
2255 if (patchRemoved) {
2256 mpClientInterface->onAudioPatchListUpdate();
2257 }
Eric Laurentd4692962014-05-05 18:13:44 -07002258}
2259
Eric Laurente0720872014-03-11 09:30:41 -07002260void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002261 int indexMin,
2262 int indexMax)
2263{
2264 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002265 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002266
2267 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002268 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2269 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002270 continue;
2271 }
2272 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002273 }
Eric Laurente552edb2014-03-10 17:42:56 -07002274}
2275
Eric Laurente0720872014-03-11 09:30:41 -07002276status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002277 int index,
2278 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
2280
Nadav Bar7c605f62017-12-25 00:01:52 +02002281 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2282 // app that has MODIFY_PHONE_STATE permission.
2283 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2284 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002285 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002286 return BAD_VALUE;
2287 }
2288 if (!audio_is_output_device(device)) {
2289 return BAD_VALUE;
2290 }
2291
2292 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002293 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002294
Eric Laurent1fd372e2016-04-06 14:23:53 -07002295 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002296 stream, device, index);
2297
Eric Laurent28d09f02016-03-08 10:43:05 -08002298 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002299 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2300 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002301 continue;
2302 }
2303 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2304 }
Eric Laurente552edb2014-03-10 17:42:56 -07002305
Eric Laurent1fd372e2016-04-06 14:23:53 -07002306 // update volume on all outputs and streams matching the following:
2307 // - The requested stream (or a stream matching for volume control) is active on the output
2308 // - The device (or devices) selected by the strategy corresponding to this stream includes
2309 // the requested device
2310 // - For non default requested device, currently selected device on the output is either the
2311 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002312 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2313 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002314 status_t status = NO_ERROR;
2315 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002316 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2317 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002318 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002319 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002320 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002321 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002322 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002323 continue;
2324 }
Eric Laurent794fde22016-03-11 09:50:45 -08002325 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002326 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2327 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002328 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2329 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002330 continue;
2331 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002332 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002333 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002334 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002335 applyVolume = (curDevice & curStreamDevice) != 0;
2336 } else {
2337 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002338 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002339 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002340 // rescale index before applying to curStream as ranges may be different for
2341 // stream and curStream
2342 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002343 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002344 //FIXME: workaround for truncated touch sounds
2345 // delayed volume change for system stream to be removed when the problem is
2346 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002347 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002348 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002349 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002350 if (volStatus != NO_ERROR) {
2351 status = volStatus;
2352 }
2353 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002354 }
Eric Laurente552edb2014-03-10 17:42:56 -07002355 }
2356 return status;
2357}
2358
Eric Laurente0720872014-03-11 09:30:41 -07002359status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002360 int *index,
2361 audio_devices_t device)
2362{
2363 if (index == NULL) {
2364 return BAD_VALUE;
2365 }
2366 if (!audio_is_output_device(device)) {
2367 return BAD_VALUE;
2368 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002369 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002370 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002371 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002372 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2373 }
François Gaffiedfd74092015-03-19 12:10:59 +01002374 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002375
François Gaffied1ab2bd2015-12-02 18:20:06 +01002376 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002377 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2378 return NO_ERROR;
2379}
2380
Eric Laurent36829f92017-04-07 19:04:42 -07002381audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002382{
2383 // select one output among several suitable for global effects.
2384 // The priority is as follows:
2385 // 1: An offloaded output. If the effect ends up not being offloadable,
2386 // AudioFlinger will invalidate the track and the offloaded output
2387 // will be closed causing the effect to be moved to a PCM output.
2388 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002389 // 3: The primary output
2390 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002391
Eric Laurent3b73df72014-03-11 09:06:29 -07002392 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002393 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002394 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002395
Eric Laurent36829f92017-04-07 19:04:42 -07002396 if (outputs.size() == 0) {
2397 return AUDIO_IO_HANDLE_NONE;
2398 }
Eric Laurente552edb2014-03-10 17:42:56 -07002399
Eric Laurent36829f92017-04-07 19:04:42 -07002400 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2401 bool activeOnly = true;
2402
2403 while (output == AUDIO_IO_HANDLE_NONE) {
2404 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2405 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2406 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2407
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002408 for (audio_io_handle_t output : outputs) {
2409 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002410 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2411 continue;
2412 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002413 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2414 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002415 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002416 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002417 }
2418 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002419 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002420 }
2421 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002422 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002423 }
2424 }
2425 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2426 output = outputOffloaded;
2427 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2428 output = outputDeepBuffer;
2429 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2430 output = outputPrimary;
2431 } else {
2432 output = outputs[0];
2433 }
2434 activeOnly = false;
2435 }
2436
2437 if (output != mMusicEffectOutput) {
2438 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2439 mMusicEffectOutput = output;
2440 }
2441
2442 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002443 return output;
2444}
2445
Eric Laurent36829f92017-04-07 19:04:42 -07002446audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2447{
2448 return selectOutputForMusicEffects();
2449}
2450
Eric Laurente0720872014-03-11 09:30:41 -07002451status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002452 audio_io_handle_t io,
2453 uint32_t strategy,
2454 int session,
2455 int id)
2456{
2457 ssize_t index = mOutputs.indexOfKey(io);
2458 if (index < 0) {
2459 index = mInputs.indexOfKey(io);
2460 if (index < 0) {
2461 ALOGW("registerEffect() unknown io %d", io);
2462 return INVALID_OPERATION;
2463 }
2464 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002465 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002466}
2467
Eric Laurentc75307b2015-03-17 15:29:32 -07002468bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2469{
Eric Laurent28d09f02016-03-08 10:43:05 -08002470 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002471 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2472 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002473 continue;
2474 }
2475 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2476 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002477 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002478}
2479
2480bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2481{
2482 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2483}
2484
Eric Laurente0720872014-03-11 09:30:41 -07002485bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002486{
2487 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002488 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002489 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002490 return true;
2491 }
2492 }
2493 return false;
2494}
2495
Eric Laurent275e8e92014-11-30 15:14:47 -08002496// Register a list of custom mixes with their attributes and format.
2497// When a mix is registered, corresponding input and output profiles are
2498// added to the remote submix hw module. The profile contains only the
2499// parameters (sampling rate, format...) specified by the mix.
2500// The corresponding input remote submix device is also connected.
2501//
2502// When a remote submix device is connected, the address is checked to select the
2503// appropriate profile and the corresponding input or output stream is opened.
2504//
2505// When capture starts, getInputForAttr() will:
2506// - 1 look for a mix matching the address passed in attribtutes tags if any
2507// - 2 if none found, getDeviceForInputSource() will:
2508// - 2.1 look for a mix matching the attributes source
2509// - 2.2 if none found, default to device selection by policy rules
2510// At this time, the corresponding output remote submix device is also connected
2511// and active playback use cases can be transferred to this mix if needed when reconnecting
2512// after AudioTracks are invalidated
2513//
2514// When playback starts, getOutputForAttr() will:
2515// - 1 look for a mix matching the address passed in attribtutes tags if any
2516// - 2 if none found, look for a mix matching the attributes usage
2517// - 3 if none found, default to device and output selection by policy rules.
2518
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002519status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002520{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2522 status_t res = NO_ERROR;
2523
2524 sp<HwModule> rSubmixModule;
2525 // examine each mix's route type
2526 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002529 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 break;
2532 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002536 rSubmixModule = mHwModules.getModuleFromName(
2537 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2538 if (rSubmixModule == 0) {
2539 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2540 i);
2541 res = INVALID_OPERATION;
2542 break;
2543 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002545
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 String8 address = mix.mDeviceAddress;
2547 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2548 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2549 } else {
2550 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2551 }
François Gaffie036e1e92015-03-19 10:16:24 +01002552
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002554 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 res = INVALID_OPERATION;
2556 break;
2557 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 audio_config_t outputConfig = mix.mFormat;
2559 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2561 // stereo and let audio flinger do the channel conversion if needed.
2562 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2563 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2564 rSubmixModule->addOutputProfile(address, &outputConfig,
2565 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2566 rSubmixModule->addInputProfile(address, &inputConfig,
2567 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002568
Eric Laurent97ac8712018-07-27 18:59:02 -07002569 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2571 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2572 address.string(), "remote-submix");
2573 } else {
2574 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2575 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2576 address.string(), "remote-submix");
2577 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002578 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2579 String8 address = mix.mDeviceAddress;
2580 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002581 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2582 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002584 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2587 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2588 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2589 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2590 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002591 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2592 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002593 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002595 } else {
2596 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002597 }
2598 break;
2599 }
2600 }
2601
2602 if (res != NO_ERROR) {
2603 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002604 i, device, address.string());
2605 res = INVALID_OPERATION;
2606 break;
2607 } else if (!foundOutput) {
2608 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2609 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002610 res = INVALID_OPERATION;
2611 break;
2612 }
Eric Laurentc722f302014-12-10 11:21:49 -08002613 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002614 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 if (res != NO_ERROR) {
2616 unregisterPolicyMixes(mixes);
2617 }
2618 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002619}
2620
2621status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2622{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002623 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002624 status_t res = NO_ERROR;
2625 sp<HwModule> rSubmixModule;
2626 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002627 for (const auto& mix : mixes) {
2628 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002629
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002630 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002631 rSubmixModule = mHwModules.getModuleFromName(
2632 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2633 if (rSubmixModule == 0) {
2634 res = INVALID_OPERATION;
2635 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 }
2637 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002638
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002639 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002640
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002641 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2642 res = INVALID_OPERATION;
2643 continue;
2644 }
2645
2646 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2647 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2648 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2649 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2650 address.string(), "remote-submix");
2651 }
2652 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2653 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2654 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2655 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2656 address.string(), "remote-submix");
2657 }
2658 rSubmixModule->removeOutputProfile(address);
2659 rSubmixModule->removeInputProfile(address);
2660
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002661 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2662 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002663 res = INVALID_OPERATION;
2664 continue;
2665 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002666 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002667 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002668 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002669}
2670
Andy Hungc29d82b2018-10-05 12:23:17 -07002671void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002672{
Andy Hungc29d82b2018-10-05 12:23:17 -07002673 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2674 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002675 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002676 std::string stateLiteral;
2677 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002678 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002679 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2680 "communications", "media", "record", "dock", "system",
2681 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2682 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2683 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002684 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002685 forceUses[i], mEngine->getForceUse(i));
2686 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002687 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2688 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2689 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2690 mAvailableOutputDevices.dump(dst, String8("Available output"));
2691 mAvailableInputDevices.dump(dst, String8("Available input"));
2692 mHwModulesAll.dump(dst);
2693 mOutputs.dump(dst);
2694 mInputs.dump(dst);
2695 mVolumeCurves->dump(dst);
2696 mEffects.dump(dst);
2697 mAudioPatches.dump(dst);
2698 mPolicyMixes.dump(dst);
2699 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002700 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002701 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002702 size_t i = 0;
2703 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002704 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002705 std::string sfmt;
2706 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002707 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002708 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002709 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002710 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002711}
2712
2713status_t AudioPolicyManager::dump(int fd)
2714{
2715 String8 result;
2716 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002717 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002718 return NO_ERROR;
2719}
2720
2721// This function checks for the parameters which can be offloaded.
2722// This can be enhanced depending on the capability of the DSP and policy
2723// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002724bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002725{
2726 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002727 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002728 offloadInfo.sample_rate, offloadInfo.channel_mask,
2729 offloadInfo.format,
2730 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2731 offloadInfo.has_video);
2732
Andy Hung2ddee192015-12-18 17:34:44 -08002733 if (mMasterMono) {
2734 return false; // no offloading if mono is set.
2735 }
2736
Eric Laurente552edb2014-03-10 17:42:56 -07002737 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002738 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2739 ALOGV("offload disabled by audio.offload.disable");
2740 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002741 }
2742
2743 // Check if stream type is music, then only allow offload as of now.
2744 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2745 {
2746 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2747 return false;
2748 }
2749
2750 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002751 const bool allowOffloadWithVideo =
2752 property_get_bool("audio.offload.video", false /* default_value */);
2753 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002754 ALOGV("isOffloadSupported: has_video == true, returning false");
2755 return false;
2756 }
2757
2758 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002759 const int min_duration_secs = property_get_int32(
2760 "audio.offload.min.duration.secs", -1 /* default_value */);
2761 if (min_duration_secs >= 0) {
2762 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2763 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2764 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002765 return false;
2766 }
2767 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2768 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2769 return false;
2770 }
2771
2772 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2773 // creating an offloaded track and tearing it down immediately after start when audioflinger
2774 // detects there is an active non offloadable effect.
2775 // FIXME: We should check the audio session here but we do not have it in this context.
2776 // This may prevent offloading in rare situations where effects are left active by apps
2777 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002778 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002779 return false;
2780 }
2781
2782 // See if there is a profile to support this.
2783 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002784 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002785 offloadInfo.sample_rate,
2786 offloadInfo.format,
2787 offloadInfo.channel_mask,
2788 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002789 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2790 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002791}
2792
Eric Laurent6a94d692014-05-20 11:18:06 -07002793status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2794 audio_port_type_t type,
2795 unsigned int *num_ports,
2796 struct audio_port *ports,
2797 unsigned int *generation)
2798{
2799 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2800 generation == NULL) {
2801 return BAD_VALUE;
2802 }
2803 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2804 if (ports == NULL) {
2805 *num_ports = 0;
2806 }
2807
2808 size_t portsWritten = 0;
2809 size_t portsMax = *num_ports;
2810 *num_ports = 0;
2811 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002812 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2813 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002814 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002815 for (const auto& dev : mAvailableOutputDevices) {
2816 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002817 continue;
2818 }
2819 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002820 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002821 }
2822 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002824 }
2825 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002826 for (const auto& dev : mAvailableInputDevices) {
2827 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002828 continue;
2829 }
2830 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002831 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002832 }
2833 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002835 }
2836 }
2837 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2838 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2839 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2840 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2841 }
2842 *num_ports += mInputs.size();
2843 }
2844 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002845 size_t numOutputs = 0;
2846 for (size_t i = 0; i < mOutputs.size(); i++) {
2847 if (!mOutputs[i]->isDuplicated()) {
2848 numOutputs++;
2849 if (portsWritten < portsMax) {
2850 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2851 }
2852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
Eric Laurent84c70242014-06-23 08:46:27 -07002854 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002855 }
2856 }
2857 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002858 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002859 return NO_ERROR;
2860}
2861
Eric Laurent99fcae42018-05-17 16:59:18 -07002862status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002863{
Eric Laurent99fcae42018-05-17 16:59:18 -07002864 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2865 return BAD_VALUE;
2866 }
2867 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2868 if (dev != 0) {
2869 dev->toAudioPort(port);
2870 return NO_ERROR;
2871 }
2872 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2873 if (dev != 0) {
2874 dev->toAudioPort(port);
2875 return NO_ERROR;
2876 }
2877 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2878 if (out != 0) {
2879 out->toAudioPort(port);
2880 return NO_ERROR;
2881 }
2882 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2883 if (in != 0) {
2884 in->toAudioPort(port);
2885 return NO_ERROR;
2886 }
2887 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002888}
2889
Eric Laurent6a94d692014-05-20 11:18:06 -07002890status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2891 audio_patch_handle_t *handle,
2892 uid_t uid)
2893{
2894 ALOGV("createAudioPatch()");
2895
2896 if (handle == NULL || patch == NULL) {
2897 return BAD_VALUE;
2898 }
2899 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2900
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002901 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002902 return BAD_VALUE;
2903 }
2904 // only one source per audio patch supported for now
2905 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 return INVALID_OPERATION;
2907 }
Eric Laurent874c42872014-08-08 15:13:39 -07002908
2909 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 return INVALID_OPERATION;
2911 }
Eric Laurent874c42872014-08-08 15:13:39 -07002912 for (size_t i = 0; i < patch->num_sinks; i++) {
2913 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2914 return INVALID_OPERATION;
2915 }
2916 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002917
2918 sp<AudioPatch> patchDesc;
2919 ssize_t index = mAudioPatches.indexOfKey(*handle);
2920
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2922 patch->sources[0].role,
2923 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002924#if LOG_NDEBUG == 0
2925 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002926 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002927 patch->sinks[i].role,
2928 patch->sinks[i].type);
2929 }
2930#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002931
2932 if (index >= 0) {
2933 patchDesc = mAudioPatches.valueAt(index);
2934 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2935 mUidCached, patchDesc->mUid, uid);
2936 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2937 return INVALID_OPERATION;
2938 }
2939 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002940 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002941 }
2942
2943 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002944 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002945 if (outputDesc == NULL) {
2946 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2947 return BAD_VALUE;
2948 }
Eric Laurent84c70242014-06-23 08:46:27 -07002949 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2950 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002951 if (patchDesc != 0) {
2952 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2953 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2954 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2955 return BAD_VALUE;
2956 }
2957 }
Eric Laurent874c42872014-08-08 15:13:39 -07002958 DeviceVector devices;
2959 for (size_t i = 0; i < patch->num_sinks; i++) {
2960 // Only support mix to devices connection
2961 // TODO add support for mix to mix connection
2962 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2963 ALOGV("createAudioPatch() source mix but sink is not a device");
2964 return INVALID_OPERATION;
2965 }
2966 sp<DeviceDescriptor> devDesc =
2967 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2968 if (devDesc == 0) {
2969 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2970 return BAD_VALUE;
2971 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002972
François Gaffie53615e22015-03-19 09:24:12 +01002973 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002974 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002975 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002976 NULL, // updatedSamplingRate
2977 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002978 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002979 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002980 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002981 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002982 ALOGV("createAudioPatch() profile not supported for device %08x",
2983 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002984 return INVALID_OPERATION;
2985 }
2986 devices.add(devDesc);
2987 }
2988 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002989 return INVALID_OPERATION;
2990 }
Eric Laurent874c42872014-08-08 15:13:39 -07002991
Eric Laurent6a94d692014-05-20 11:18:06 -07002992 // TODO: reconfigure output format and channels here
2993 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002994 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002995 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 index = mAudioPatches.indexOfKey(*handle);
2997 if (index >= 0) {
2998 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2999 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3000 }
3001 patchDesc = mAudioPatches.valueAt(index);
3002 patchDesc->mUid = uid;
3003 ALOGV("createAudioPatch() success");
3004 } else {
3005 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3006 return INVALID_OPERATION;
3007 }
3008 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3009 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3010 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003011 // only one sink supported when connecting an input device to a mix
3012 if (patch->num_sinks > 1) {
3013 return INVALID_OPERATION;
3014 }
François Gaffie53615e22015-03-19 09:24:12 +01003015 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003016 if (inputDesc == NULL) {
3017 return BAD_VALUE;
3018 }
3019 if (patchDesc != 0) {
3020 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3021 return BAD_VALUE;
3022 }
3023 }
3024 sp<DeviceDescriptor> devDesc =
3025 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3026 if (devDesc == 0) {
3027 return BAD_VALUE;
3028 }
3029
François Gaffie53615e22015-03-19 09:24:12 +01003030 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003031 devDesc->mAddress,
3032 patch->sinks[0].sample_rate,
3033 NULL, /*updatedSampleRate*/
3034 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003035 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003036 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003037 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003038 // FIXME for the parameter type,
3039 // and the NONE
3040 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003041 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 return INVALID_OPERATION;
3043 }
3044 // TODO: reconfigure output format and channels here
3045 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003046 devDesc->type(), inputDesc->mIoHandle);
3047 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 index = mAudioPatches.indexOfKey(*handle);
3049 if (index >= 0) {
3050 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3051 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3052 }
3053 patchDesc = mAudioPatches.valueAt(index);
3054 patchDesc->mUid = uid;
3055 ALOGV("createAudioPatch() success");
3056 } else {
3057 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3058 return INVALID_OPERATION;
3059 }
3060 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3061 // device to device connection
3062 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003063 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003064 return BAD_VALUE;
3065 }
3066 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 sp<DeviceDescriptor> srcDeviceDesc =
3068 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003069 if (srcDeviceDesc == 0) {
3070 return BAD_VALUE;
3071 }
Eric Laurent874c42872014-08-08 15:13:39 -07003072
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 //update source and sink with our own data as the data passed in the patch may
3074 // be incomplete.
3075 struct audio_patch newPatch = *patch;
3076 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003077
Eric Laurent874c42872014-08-08 15:13:39 -07003078 for (size_t i = 0; i < patch->num_sinks; i++) {
3079 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3080 ALOGV("createAudioPatch() source device but one sink is not a device");
3081 return INVALID_OPERATION;
3082 }
3083
3084 sp<DeviceDescriptor> sinkDeviceDesc =
3085 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3086 if (sinkDeviceDesc == 0) {
3087 return BAD_VALUE;
3088 }
3089 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3090
Eric Laurent3bcf8592015-04-03 12:13:24 -07003091 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003092 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003093 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003094 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003095 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003096 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003097 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003098 return INVALID_OPERATION;
3099 }
Eric Laurent874c42872014-08-08 15:13:39 -07003100 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003101 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003102 // if the sink device is reachable via an opened output stream, request to go via
3103 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003104 audio_io_handle_t output = selectOutput(outputs,
3105 AUDIO_OUTPUT_FLAG_NONE,
3106 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003107 if (output != AUDIO_IO_HANDLE_NONE) {
3108 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3109 if (outputDesc->isDuplicated()) {
3110 return INVALID_OPERATION;
3111 }
3112 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003113 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003114 newPatch.num_sources = 2;
3115 }
Eric Laurent83b88082014-06-20 18:31:16 -07003116 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 }
3118 // TODO: check from routing capabilities in config file and other conflicting patches
3119
Mikhail Naganovdc769682018-05-04 15:34:08 -07003120 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3121 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3123 status);
3124 return INVALID_OPERATION;
3125 }
3126 } else {
3127 return BAD_VALUE;
3128 }
3129 } else {
3130 return BAD_VALUE;
3131 }
3132 return NO_ERROR;
3133}
3134
3135status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3136 uid_t uid)
3137{
3138 ALOGV("releaseAudioPatch() patch %d", handle);
3139
3140 ssize_t index = mAudioPatches.indexOfKey(handle);
3141
3142 if (index < 0) {
3143 return BAD_VALUE;
3144 }
3145 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3146 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3147 mUidCached, patchDesc->mUid, uid);
3148 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3149 return INVALID_OPERATION;
3150 }
3151
3152 struct audio_patch *patch = &patchDesc->mPatch;
3153 patchDesc->mUid = mUidCached;
3154 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003156 if (outputDesc == NULL) {
3157 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3158 return BAD_VALUE;
3159 }
3160
Eric Laurentc75307b2015-03-17 15:29:32 -07003161 setOutputDevice(outputDesc,
3162 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003163 true,
3164 0,
3165 NULL);
3166 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3167 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003168 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 if (inputDesc == NULL) {
3170 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3171 return BAD_VALUE;
3172 }
3173 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003174 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003175 true,
3176 NULL);
3177 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3179 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3180 status, patchDesc->mAfPatchHandle);
3181 removeAudioPatch(patchDesc->mHandle);
3182 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003183 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003184 } else {
3185 return BAD_VALUE;
3186 }
3187 } else {
3188 return BAD_VALUE;
3189 }
3190 return NO_ERROR;
3191}
3192
3193status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3194 struct audio_patch *patches,
3195 unsigned int *generation)
3196{
François Gaffie53615e22015-03-19 09:24:12 +01003197 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 return BAD_VALUE;
3199 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003201 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003202}
3203
Eric Laurente1715a42014-05-20 11:30:42 -07003204status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003205{
Eric Laurente1715a42014-05-20 11:30:42 -07003206 ALOGV("setAudioPortConfig()");
3207
3208 if (config == NULL) {
3209 return BAD_VALUE;
3210 }
3211 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3212 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003213 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3214 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003215 }
3216
Eric Laurenta121f902014-06-03 13:32:54 -07003217 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003218 if (config->type == AUDIO_PORT_TYPE_MIX) {
3219 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003220 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003221 if (outputDesc == NULL) {
3222 return BAD_VALUE;
3223 }
Eric Laurent84c70242014-06-23 08:46:27 -07003224 ALOG_ASSERT(!outputDesc->isDuplicated(),
3225 "setAudioPortConfig() called on duplicated output %d",
3226 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003227 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003228 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003229 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003230 if (inputDesc == NULL) {
3231 return BAD_VALUE;
3232 }
Eric Laurenta121f902014-06-03 13:32:54 -07003233 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003234 } else {
3235 return BAD_VALUE;
3236 }
3237 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3238 sp<DeviceDescriptor> deviceDesc;
3239 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3240 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3241 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3242 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3243 } else {
3244 return BAD_VALUE;
3245 }
3246 if (deviceDesc == NULL) {
3247 return BAD_VALUE;
3248 }
Eric Laurenta121f902014-06-03 13:32:54 -07003249 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003250 } else {
3251 return BAD_VALUE;
3252 }
3253
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003254 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003255 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3256 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003257 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003258 audioPortConfig->toAudioPortConfig(&newConfig, config);
3259 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003260 }
Eric Laurenta121f902014-06-03 13:32:54 -07003261 if (status != NO_ERROR) {
3262 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003263 }
Eric Laurente1715a42014-05-20 11:30:42 -07003264
3265 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003266}
3267
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003268void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3269{
Eric Laurentd60560a2015-04-10 11:31:20 -07003270 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003271 clearAudioPatches(uid);
3272 clearSessionRoutes(uid);
3273}
3274
Eric Laurent6a94d692014-05-20 11:18:06 -07003275void AudioPolicyManager::clearAudioPatches(uid_t uid)
3276{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003277 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003278 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3279 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003280 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003281 }
3282 }
3283}
3284
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003285void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3286 audio_io_handle_t ouptutToSkip)
3287{
3288 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3289 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3290 for (size_t j = 0; j < mOutputs.size(); j++) {
3291 if (mOutputs.keyAt(j) == ouptutToSkip) {
3292 continue;
3293 }
3294 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3295 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3296 continue;
3297 }
3298 // If the default device for this strategy is on another output mix,
3299 // invalidate all tracks in this strategy to force re connection.
3300 // Otherwise select new device on the output mix.
3301 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003302 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003303 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3304 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3305 }
3306 }
3307 } else {
3308 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3309 setOutputDevice(outputDesc, newDevice, false);
3310 }
3311 }
3312}
3313
3314void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3315{
3316 // remove output routes associated with this uid
3317 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003318 for (size_t i = 0; i < mOutputs.size(); i++) {
3319 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003320 for (const auto& client : outputDesc->getClientIterable()) {
3321 if (client->hasPreferredDevice() && client->uid() == uid) {
3322 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3323 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003324 }
3325 }
3326 }
3327 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003328 for (const auto& strategy : affectedStrategies) {
3329 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003330 }
3331
3332 // remove input routes associated with this uid
3333 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003334 for (size_t i = 0; i < mInputs.size(); i++) {
3335 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003336 for (const auto& client : inputDesc->getClientIterable()) {
3337 if (client->hasPreferredDevice() && client->uid() == uid) {
3338 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3339 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003340 }
3341 }
3342 }
3343 // reroute inputs if necessary
3344 SortedVector<audio_io_handle_t> inputsToClose;
3345 for (size_t i = 0; i < mInputs.size(); i++) {
3346 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003347 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348 inputsToClose.add(inputDesc->mIoHandle);
3349 }
3350 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003351 for (const auto& input : inputsToClose) {
3352 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003353 }
3354}
3355
Eric Laurentd60560a2015-04-10 11:31:20 -07003356void AudioPolicyManager::clearAudioSources(uid_t uid)
3357{
3358 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003359 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3360 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003361 stopAudioSource(mAudioSources.keyAt(i));
3362 }
3363 }
3364}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003365
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003366status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3367 audio_io_handle_t *ioHandle,
3368 audio_devices_t *device)
3369{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003370 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3371 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003372 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003373
François Gaffiedf372692015-03-19 10:43:27 +01003374 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003375}
3376
Eric Laurentd60560a2015-04-10 11:31:20 -07003377status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003378 const audio_attributes_t *attributes,
3379 audio_port_handle_t *portId,
3380 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003381{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003382 ALOGV("%s", __FUNCTION__);
3383 *portId = AUDIO_PORT_HANDLE_NONE;
3384
3385 if (source == NULL || attributes == NULL || portId == NULL) {
3386 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3387 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003388 return BAD_VALUE;
3389 }
3390
Eric Laurentd60560a2015-04-10 11:31:20 -07003391 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3392 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003393 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3394 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003395 return INVALID_OPERATION;
3396 }
3397
3398 sp<DeviceDescriptor> srcDeviceDesc =
3399 mAvailableInputDevices.getDevice(source->ext.device.type,
3400 String8(source->ext.device.address));
3401 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003402 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003403 return BAD_VALUE;
3404 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003405
3406 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003407
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003408 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003409 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003410
3411 sp<SourceClientDescriptor> sourceDesc =
3412 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003413 streamTypefromAttributesInt(attributes),
3414 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003415
3416 status_t status = connectAudioSource(sourceDesc);
3417 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003419 }
3420 return status;
3421}
3422
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003424{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003425 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003426
3427 // make sure we only have one patch per source.
3428 disconnectAudioSource(sourceDesc);
3429
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003430 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003431 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003432 audio_stream_type_t stream = sourceDesc->stream();
3433 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003434
3435 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3436 sp<DeviceDescriptor> sinkDeviceDesc =
3437 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3438
3439 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003440
3441 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3442 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003443 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3445 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3446 // create patch between src device and output device
3447 // create Hwoutput and add to mHwOutputs
3448 } else {
3449 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3450 audio_io_handle_t output =
3451 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3452 if (output == AUDIO_IO_HANDLE_NONE) {
3453 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3454 return INVALID_OPERATION;
3455 }
3456 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3457 if (outputDesc->isDuplicated()) {
3458 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3459 return INVALID_OPERATION;
3460 }
Eric Laurent733ce942017-12-07 12:18:25 -08003461 status_t status = outputDesc->start();
3462 if (status != NO_ERROR) {
3463 return status;
3464 }
3465
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 // create a special patch with no sink and two sources:
3467 // - the second source indicates to PatchPanel through which output mix this patch should
3468 // be connected as well as the stream type for volume control
3469 // - the sink is defined by whatever output device is currently selected for the output
3470 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003471 PatchBuilder patchBuilder;
3472 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3473 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003474 &afPatchHandle,
3475 0);
3476 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3477 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003478 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 if (status != NO_ERROR) {
3480 ALOGW("%s patch panel could not connect device patch, error %d",
3481 __FUNCTION__, status);
3482 return INVALID_OPERATION;
3483 }
3484 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003485 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003486
3487 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003488 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003489 return status;
3490 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003491 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003492 if (delayMs != 0) {
3493 usleep(delayMs * 1000);
3494 }
3495 }
3496
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003497 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3498 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003499
3500 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003501}
3502
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003503status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003504{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3506 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003508 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003509 return BAD_VALUE;
3510 }
3511 status_t status = disconnectAudioSource(sourceDesc);
3512
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003513 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514 return status;
3515}
3516
Andy Hung2ddee192015-12-18 17:34:44 -08003517status_t AudioPolicyManager::setMasterMono(bool mono)
3518{
3519 if (mMasterMono == mono) {
3520 return NO_ERROR;
3521 }
3522 mMasterMono = mono;
3523 // if enabling mono we close all offloaded devices, which will invalidate the
3524 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3525 // for recreating the new AudioTrack as non-offloaded PCM.
3526 //
3527 // If disabling mono, we leave all tracks as is: we don't know which clients
3528 // and tracks are able to be recreated as offloaded. The next "song" should
3529 // play back offloaded.
3530 if (mMasterMono) {
3531 Vector<audio_io_handle_t> offloaded;
3532 for (size_t i = 0; i < mOutputs.size(); ++i) {
3533 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3534 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3535 offloaded.push(desc->mIoHandle);
3536 }
3537 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003538 for (const auto& handle : offloaded) {
3539 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003540 }
3541 }
3542 // update master mono for all remaining outputs
3543 for (size_t i = 0; i < mOutputs.size(); ++i) {
3544 updateMono(mOutputs.keyAt(i));
3545 }
3546 return NO_ERROR;
3547}
3548
3549status_t AudioPolicyManager::getMasterMono(bool *mono)
3550{
3551 *mono = mMasterMono;
3552 return NO_ERROR;
3553}
3554
Eric Laurentac9cef52017-06-09 15:46:26 -07003555float AudioPolicyManager::getStreamVolumeDB(
3556 audio_stream_type_t stream, int index, audio_devices_t device)
3557{
3558 return computeVolume(stream, index, device);
3559}
3560
jiabin81772902018-04-02 17:52:27 -07003561status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3562 audio_format_t *surroundFormats,
3563 bool *surroundFormatsEnabled,
3564 bool reported)
3565{
3566 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3567 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3568 return BAD_VALUE;
3569 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003570 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3571 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003572
3573 // Only return value if there is HDMI output.
3574 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3575 return INVALID_OPERATION;
3576 }
3577
3578 size_t formatsWritten = 0;
3579 size_t formatsMax = *numSurroundFormats;
3580 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003581 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003582 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003583 // Return formats from HDMI profiles, that have already been resolved by
3584 // checkOutputsForDevice().
3585 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3586 AUDIO_DEVICE_OUT_HDMI);
3587 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3588 FormatVector supportedFormats =
3589 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3590 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003591 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003592 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003593 } else {
3594 for (const auto& pair : mConfig.getSurroundFormats()) {
3595 if (pair.second.count(supportedFormats[j]) != 0) {
3596 formats.insert(pair.first);
3597 break;
3598 }
3599 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003600 }
3601 }
jiabin81772902018-04-02 17:52:27 -07003602 }
3603 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003604 for (const auto& pair : mConfig.getSurroundFormats()) {
3605 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003606 }
3607 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003608 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003609 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003610 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003611 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003612 if (mConfig.getSurroundFormats().count(format) == 0) {
3613 // Check sub-formats
3614 for (const auto& pair : mConfig.getSurroundFormats()) {
3615 for (const auto& subformat : pair.second) {
3616 formatEnabled = mSurroundFormats.count(subformat) != 0;
3617 if (formatEnabled) break;
3618 }
3619 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003620 }
3621 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003622 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003623 }
3624 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3625 }
3626 (*numSurroundFormats)++;
3627 }
3628 return NO_ERROR;
3629}
3630
3631status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3632{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003633 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003634 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003635 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3636 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003637 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003638 return BAD_VALUE;
3639 }
3640
3641 // Should only be called when MANUAL.
3642 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3643 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3644 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003645 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003646 return INVALID_OPERATION;
3647 }
3648
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003649 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003650 return NO_ERROR;
3651 }
3652
3653 // The operation is valid only when there is HDMI output available.
3654 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003655 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003656 return INVALID_OPERATION;
3657 }
3658
Mikhail Naganov2563f232018-09-27 14:48:01 -07003659 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003660 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003661 mSurroundFormats.insert(audioFormat);
3662 for (const auto& subFormat : formatIter->second) {
3663 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003664 }
3665 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003666 mSurroundFormats.erase(audioFormat);
3667 for (const auto& subFormat : formatIter->second) {
3668 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003669 }
3670 }
3671
3672 sp<SwAudioOutputDescriptor> outputDesc;
3673 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003674 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003675 AUDIO_DEVICE_OUT_HDMI);
3676 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3677 // Simulate reconnection to update enabled surround sound formats.
3678 String8 address = hdmiOutputDevices[i]->mAddress;
3679 String8 name = hdmiOutputDevices[i]->getName();
3680 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3681 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3682 address.c_str(),
3683 name.c_str());
3684 if (status != NO_ERROR) {
3685 continue;
3686 }
3687 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3688 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3689 address.c_str(),
3690 name.c_str());
3691 profileUpdated |= (status == NO_ERROR);
3692 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003693 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003694 AUDIO_DEVICE_IN_HDMI);
3695 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3696 // Simulate reconnection to update enabled surround sound formats.
3697 String8 address = hdmiInputDevices[i]->mAddress;
3698 String8 name = hdmiInputDevices[i]->getName();
3699 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 if (status != NO_ERROR) {
3704 continue;
3705 }
3706 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3707 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3708 address.c_str(),
3709 name.c_str());
3710 profileUpdated |= (status == NO_ERROR);
3711 }
3712
jiabin81772902018-04-02 17:52:27 -07003713 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003714 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003715 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003716 }
3717
3718 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3719}
3720
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003721void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3722{
3723 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3724
3725 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3726 for (size_t i = 0; i < activeInputs.size(); i++) {
3727 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003728 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3729 for (const auto& client : clients) {
3730 if (uid == client->uid()) {
3731 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003732 }
3733 }
3734 }
3735}
3736
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003737status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003738{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003739 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003740
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003741 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003742 if (patchDesc == 0) {
3743 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003744 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003745 return BAD_VALUE;
3746 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003747 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003748
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003749 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003750 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003751 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003752 if (status == NO_ERROR) {
3753 swOutputDesc->stop();
3754 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003755 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3756 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003757 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003758 if (hwOutputDesc != 0) {
3759 // release patch between src device and output device
3760 // close Hwoutput and remove from mHwOutputs
3761 } else {
3762 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3763 }
3764 }
3765 return NO_ERROR;
3766}
3767
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003769 audio_io_handle_t output, routing_strategy strategy)
3770{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003772 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003773 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3774 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003775 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003776 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003777 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3778 source = sourceDesc;
3779 break;
3780 }
3781 }
3782 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003783}
3784
Eric Laurente552edb2014-03-10 17:42:56 -07003785// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003786// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003787// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003788uint32_t AudioPolicyManager::nextAudioPortGeneration()
3789{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003790 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003791}
3792
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003793#ifdef USE_XML_AUDIO_POLICY_CONF
3794// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3795static const char *kConfigLocationList[] =
3796 {"/odm/etc", "/vendor/etc", "/system/etc"};
3797static const int kConfigLocationListSize =
3798 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3799
3800static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3801 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003802 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003803 status_t ret;
3804
Petri Gyntherf497f292018-04-17 18:46:10 -07003805 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3806 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3807 // A2DP offload supported but disabled: try to use special XML file
3808 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3809 }
3810 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3811
3812 for (const char* fileName : fileNames) {
3813 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003814 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3815 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003816 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003817 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003818 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003819 return ret;
3820 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003821 }
3822 }
3823 return ret;
3824}
3825#endif
3826
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003827AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3828 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003829 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003830 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003831 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003832 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003833 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003834#ifdef USE_XML_AUDIO_POLICY_CONF
3835 mVolumeCurves(new VolumeCurvesCollection()),
3836 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003837 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003838#else
3839 mVolumeCurves(new StreamDescriptorCollection()),
3840 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3841 mDefaultOutputDevice),
3842#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003843 mAudioPortGeneration(1),
3844 mBeaconMuteRefCount(0),
3845 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003846 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003847 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003848 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003849 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3850 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003851{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003852}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003853
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003854AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3855 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3856{
3857 loadConfig();
3858 initialize();
3859}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003860
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003862#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003864#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3866 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003867#endif
3868 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003870 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003871}
3872
3873status_t AudioPolicyManager::initialize() {
3874 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003875
3876 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003877 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3878 if (!engineInstance) {
3879 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003880 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003881 }
3882 // Retrieve the Policy Manager Interface
3883 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3884 if (mEngine == NULL) {
3885 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003886 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003887 }
3888 mEngine->setObserver(this);
3889 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890 if (status != NO_ERROR) {
3891 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3892 return status;
3893 }
François Gaffie2110e042015-03-24 08:41:51 +01003894
Eric Laurent3a4311c2014-03-17 12:00:47 -07003895 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003896 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003897 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3898 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003899 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003900 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003901 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3902 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003903 continue;
3904 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003905 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003906 // open all output streams needed to access attached devices
3907 // except for direct output streams that are only opened when they are actually
3908 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003909 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003910 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003911 if (!outProfile->canOpenNewIo()) {
3912 ALOGE("Invalid Output profile max open count %u for profile %s",
3913 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3914 continue;
3915 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003916 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003917 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003918 continue;
3919 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003920 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003921 mTtsOutputAvailable = true;
3922 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003923
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003924 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003925 continue;
3926 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003927 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003928 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3929 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003930 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003931 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003932 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003933 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003935 if ((profileType & outputDeviceTypes) == 0) {
3936 continue;
3937 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003938 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3939 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003940 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003941 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3942 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003943 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3944 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003945 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003946 status_t status = outputDesc->open(nullptr, profileType, address,
3947 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003948
3949 if (status != NO_ERROR) {
3950 ALOGW("Cannot open output stream for device %08x on hw module %s",
3951 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003952 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003953 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003954 for (const auto& dev : supportedDevices) {
3955 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003956 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003957 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003958 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 }
3960 }
3961 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003962 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003963 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003964 }
3965 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003966 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003967 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003968 true,
3969 0,
3970 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003971 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003972 }
Eric Laurente552edb2014-03-10 17:42:56 -07003973 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003974 // open input streams needed to access attached devices to validate
3975 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003976 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003977 if (!inProfile->canOpenNewIo()) {
3978 ALOGE("Invalid Input profile max open count %u for profile %s",
3979 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3980 continue;
3981 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003982 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003983 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003984 continue;
3985 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003987 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003988 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3989
Eric Laurentd78f1532014-09-16 16:38:20 -07003990 if ((profileType & inputDeviceTypes) == 0) {
3991 continue;
3992 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003993 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003994 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003995
Mikhail Naganov708e0382018-05-30 09:53:04 -07003996 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003997 // the inputs vector must be of size >= 1, but we don't want to crash here
3998 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3999 : String8("");
4000 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4001 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4002
Eric Laurentd78f1532014-09-16 16:38:20 -07004003 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004004 status_t status = inputDesc->open(nullptr,
4005 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004006 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004007 AUDIO_SOURCE_MIC,
4008 AUDIO_INPUT_FLAG_NONE,
4009 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004010
4011 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004012 for (const auto& dev : inProfile->getSupportedDevices()) {
4013 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004014 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004015 if (index >= 0) {
4016 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4017 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004018 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004019 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004020 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004021 }
4022 }
Eric Laurentfe231122017-11-17 17:48:06 -08004023 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004024 } else {
4025 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004026 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004027 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004029 }
4030 }
4031 // make sure all attached devices have been allocated a unique ID
4032 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004033 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004034 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004035 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4036 continue;
4037 }
François Gaffie2110e042015-03-24 08:41:51 +01004038 // The device is now validated and can be appended to the available devices of the engine
4039 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4040 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004041 i++;
4042 }
4043 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004044 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004045 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004046 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4047 continue;
4048 }
François Gaffie2110e042015-03-24 08:41:51 +01004049 // The device is now validated and can be appended to the available devices of the engine
4050 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4051 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004052 i++;
4053 }
4054 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004055 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004056 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004057 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 }
jiabin9ff780e2018-03-19 18:19:52 -07004059 // If microphones address is empty, set it according to device type
4060 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4061 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4062 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4063 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4064 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4065 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4066 }
4067 }
4068 }
Eric Laurente552edb2014-03-10 17:42:56 -07004069
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004070 if (mPrimaryOutput == 0) {
4071 ALOGE("Failed to open primary output");
4072 status = NO_INIT;
4073 }
Eric Laurente552edb2014-03-10 17:42:56 -07004074
4075 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004076 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004077}
4078
Eric Laurente0720872014-03-11 09:30:41 -07004079AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004080{
Eric Laurente552edb2014-03-10 17:42:56 -07004081 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004082 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004083 }
4084 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004085 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004086 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004087 mAvailableOutputDevices.clear();
4088 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004089 mOutputs.clear();
4090 mInputs.clear();
4091 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004092 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004093 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004094}
4095
Eric Laurente0720872014-03-11 09:30:41 -07004096status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004097{
Eric Laurent87ffa392015-05-22 10:32:38 -07004098 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004099}
4100
Eric Laurente552edb2014-03-10 17:42:56 -07004101// ---
4102
Eric Laurent98e38192018-02-15 18:31:53 -08004103void AudioPolicyManager::addOutput(audio_io_handle_t output,
4104 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004105{
Eric Laurent1c333e22014-05-20 10:48:17 -07004106 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004107 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004108 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004109 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004110 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004111}
4112
François Gaffie53615e22015-03-19 09:24:12 +01004113void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4114{
4115 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004116 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004117}
4118
Eric Laurent98e38192018-02-15 18:31:53 -08004119void AudioPolicyManager::addInput(audio_io_handle_t input,
4120 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004121{
Eric Laurent1c333e22014-05-20 10:48:17 -07004122 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004124}
Eric Laurente552edb2014-03-10 17:42:56 -07004125
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004126void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004127 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004128 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004129 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004130 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004131 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004132 if (devDesc != 0) {
4133 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4134 desc->mIoHandle, address.string());
4135 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004136 }
4137}
4138
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004139status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004140 audio_policy_dev_state_t state,
4141 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004142 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004143{
François Gaffie53615e22015-03-19 09:24:12 +01004144 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004145 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004146
4147 if (audio_device_is_digital(device)) {
4148 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004149 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004150 }
Eric Laurente552edb2014-03-10 17:42:56 -07004151
Eric Laurent3b73df72014-03-11 09:06:29 -07004152 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004153 // first list already open outputs that can be routed to this device
4154 for (size_t i = 0; i < mOutputs.size(); i++) {
4155 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004156 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004157 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004158 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4159 outputs.add(mOutputs.keyAt(i));
4160 } else {
4161 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004162 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 }
Eric Laurente552edb2014-03-10 17:42:56 -07004164 }
4165 }
4166 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004167 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004168 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004169 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4170 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004171 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004172 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004173 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004174 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004175 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4176 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004177 }
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
4179 }
4180 }
4181
Eric Laurent7b279bb2015-12-14 10:18:23 -08004182 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004183
Eric Laurente552edb2014-03-10 17:42:56 -07004184 if (profiles.isEmpty() && outputs.isEmpty()) {
4185 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4186 return BAD_VALUE;
4187 }
4188
4189 // open outputs for matching profiles if needed. Direct outputs are also opened to
4190 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4191 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004192 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004193
4194 // nothing to do if one output is already opened for this profile
4195 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004196 for (j = 0; j < outputs.size(); j++) {
4197 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004198 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004199 // matching profile: save the sample rates, format and channel masks supported
4200 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004201 if (audio_device_is_digital(device)) {
4202 devDesc->importAudioPort(profile);
4203 }
Eric Laurente552edb2014-03-10 17:42:56 -07004204 break;
4205 }
4206 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004207 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004208 continue;
4209 }
4210
Eric Laurent3974e3b2017-12-07 17:58:43 -08004211 if (!profile->canOpenNewIo()) {
4212 ALOGW("Max Output number %u already opened for this profile %s",
4213 profile->maxOpenCount, profile->getTagName().c_str());
4214 continue;
4215 }
4216
Eric Laurent83efe1c2017-07-09 16:51:08 -07004217 ALOGV("opening output for device %08x with params %s profile %p name %s",
4218 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004219 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004220 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004221 status_t status = desc->open(nullptr, device, address,
4222 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004223
Eric Laurentfe231122017-11-17 17:48:06 -08004224 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004225 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004226 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004227 char *param = audio_device_address_to_parameter(device, address);
4228 mpClientInterface->setParameters(output, String8(param));
4229 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004230 }
Phil Burk00eeb322016-03-31 12:41:00 -07004231 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004232 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004233 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004234 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004235 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004236 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004237 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004238 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004239 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4240 profile->pickAudioProfile(
4241 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004242 config.offload_info.sample_rate = config.sample_rate;
4243 config.offload_info.channel_mask = config.channel_mask;
4244 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004245
4246 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4247 AUDIO_OUTPUT_FLAG_NONE, &output);
4248 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 output = AUDIO_IO_HANDLE_NONE;
4250 }
Eric Laurentd4692962014-05-05 18:13:44 -07004251 }
4252
Eric Laurentcf2c0212014-07-25 16:20:43 -07004253 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004254 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004255 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004256 sp<AudioPolicyMix> policyMix;
4257 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004258 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4259 address.string());
4260 }
François Gaffie036e1e92015-03-19 10:16:24 +01004261 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004262 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004263
Eric Laurent87ffa392015-05-22 10:32:38 -07004264 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4265 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004266 // no duplicated output for direct outputs and
4267 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004268 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004269
Eric Laurentd4692962014-05-05 18:13:44 -07004270 //TODO: configure audio effect output stage here
4271
4272 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004273 sp<SwAudioOutputDescriptor> dupOutputDesc =
4274 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4275 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4276 &duplicatedOutput);
4277 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004278 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004279 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004280 } else {
4281 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004282 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004283 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004284 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004285 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004286 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 }
4289 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004290 } else {
4291 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004293 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004294 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004295 profiles.removeAt(profile_index);
4296 profile_index--;
4297 } else {
4298 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004299 // Load digital format info only for digital devices
4300 if (audio_device_is_digital(device)) {
4301 devDesc->importAudioPort(profile);
4302 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004303
François Gaffie53615e22015-03-19 09:24:12 +01004304 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004305 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4306 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004307 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004308 NULL/*patch handle*/, address.string());
4309 }
Eric Laurente552edb2014-03-10 17:42:56 -07004310 ALOGV("checkOutputsForDevice(): adding output %d", output);
4311 }
4312 }
4313
4314 if (profiles.isEmpty()) {
4315 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4316 return BAD_VALUE;
4317 }
Eric Laurentd4692962014-05-05 18:13:44 -07004318 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004319 // check if one opened output is not needed any more after disconnecting one device
4320 for (size_t i = 0; i < mOutputs.size(); i++) {
4321 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004323 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004324 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004325 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004326 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004327 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004328 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4329 mOutputs.keyAt(i));
4330 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004331 }
Eric Laurente552edb2014-03-10 17:42:56 -07004332 }
4333 }
Eric Laurentd4692962014-05-05 18:13:44 -07004334 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004335 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004336 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4337 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004338 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004339 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004340 "clearing direct output profile %zu on module %s",
4341 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004342 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004343 }
4344 }
4345 }
4346 }
4347 return NO_ERROR;
4348}
4349
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004350status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004351 audio_policy_dev_state_t state,
4352 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004353 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004354{
Paul McLean9080a4c2015-06-18 08:24:02 -07004355 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004356 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004357
4358 if (audio_device_is_digital(device)) {
4359 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004360 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004361 }
4362
Eric Laurentd4692962014-05-05 18:13:44 -07004363 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4364 // first list already open inputs that can be routed to this device
4365 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4366 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004367 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004368 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4369 inputs.add(mInputs.keyAt(input_index));
4370 }
4371 }
4372
4373 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004374 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004375 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004376 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004377 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004378 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004379 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004380
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004381 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004382 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004383 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004384 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004385 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4386 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004387 }
Eric Laurentd4692962014-05-05 18:13:44 -07004388 }
4389 }
4390 }
4391
4392 if (profiles.isEmpty() && inputs.isEmpty()) {
4393 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4394 return BAD_VALUE;
4395 }
4396
4397 // open inputs for matching profiles if needed. Direct inputs are also opened to
4398 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4399 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4400
Eric Laurent1c333e22014-05-20 10:48:17 -07004401 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004402
Eric Laurentd4692962014-05-05 18:13:44 -07004403 // nothing to do if one input is already opened for this profile
4404 size_t input_index;
4405 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4406 desc = mInputs.valueAt(input_index);
4407 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004408 if (audio_device_is_digital(device)) {
4409 devDesc->importAudioPort(profile);
4410 }
Eric Laurentd4692962014-05-05 18:13:44 -07004411 break;
4412 }
4413 }
4414 if (input_index != mInputs.size()) {
4415 continue;
4416 }
4417
Eric Laurent3974e3b2017-12-07 17:58:43 -08004418 if (!profile->canOpenNewIo()) {
4419 ALOGW("Max Input number %u already opened for this profile %s",
4420 profile->maxOpenCount, profile->getTagName().c_str());
4421 continue;
4422 }
4423
Eric Laurentfe231122017-11-17 17:48:06 -08004424 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004425 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004426 status_t status = desc->open(nullptr,
4427 device,
4428 address,
4429 AUDIO_SOURCE_MIC,
4430 AUDIO_INPUT_FLAG_NONE,
4431 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004432
Eric Laurentcf2c0212014-07-25 16:20:43 -07004433 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004434 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004435 char *param = audio_device_address_to_parameter(device, address);
4436 mpClientInterface->setParameters(input, String8(param));
4437 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004438 }
Phil Burk00eeb322016-03-31 12:41:00 -07004439 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004440 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004441 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004442 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004443 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004444 }
4445
4446 if (input != 0) {
4447 addInput(input, desc);
4448 }
4449 } // endif input != 0
4450
Eric Laurentcf2c0212014-07-25 16:20:43 -07004451 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004452 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004453 profiles.removeAt(profile_index);
4454 profile_index--;
4455 } else {
4456 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004457 if (audio_device_is_digital(device)) {
4458 devDesc->importAudioPort(profile);
4459 }
Eric Laurentd4692962014-05-05 18:13:44 -07004460 ALOGV("checkInputsForDevice(): adding input %d", input);
4461 }
4462 } // end scan profiles
4463
4464 if (profiles.isEmpty()) {
4465 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4466 return BAD_VALUE;
4467 }
4468 } else {
4469 // Disconnect
4470 // check if one opened input is not needed any more after disconnecting one device
4471 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4472 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004473 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004474 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4475 mInputs.keyAt(input_index));
4476 inputs.add(mInputs.keyAt(input_index));
4477 }
4478 }
4479 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004480 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004481 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004482 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004483 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004484 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004485 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004486 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4487 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004488 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004489 }
4490 }
4491 }
4492 } // end disconnect
4493
4494 return NO_ERROR;
4495}
4496
4497
Eric Laurente0720872014-03-11 09:30:41 -07004498void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004499{
4500 ALOGV("closeOutput(%d)", output);
4501
Eric Laurentc75307b2015-03-17 15:29:32 -07004502 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004503 if (outputDesc == NULL) {
4504 ALOGW("closeOutput() unknown output %d", output);
4505 return;
4506 }
François Gaffie036e1e92015-03-19 10:16:24 +01004507 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004508
Eric Laurente552edb2014-03-10 17:42:56 -07004509 // look for duplicated outputs connected to the output being removed.
4510 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004511 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004512 if (dupOutputDesc->isDuplicated() &&
4513 (dupOutputDesc->mOutput1 == outputDesc ||
4514 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004515 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004516 if (dupOutputDesc->mOutput1 == outputDesc) {
4517 outputDesc2 = dupOutputDesc->mOutput2;
4518 } else {
4519 outputDesc2 = dupOutputDesc->mOutput1;
4520 }
4521 // As all active tracks on duplicated output will be deleted,
4522 // and as they were also referenced on the other output, the reference
4523 // count for their stream type must be adjusted accordingly on
4524 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004525 const bool wasActive = outputDesc2->isActive();
4526 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4527 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004528 }
Eric Laurent733ce942017-12-07 12:18:25 -08004529 // stop() will be a no op if the output is still active but is needed in case all
4530 // active streams refcounts where cleared above
4531 if (wasActive) {
4532 outputDesc2->stop();
4533 }
Eric Laurente552edb2014-03-10 17:42:56 -07004534 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4535 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4536
4537 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004538 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004539 }
4540 }
4541
Eric Laurent05b90f82014-08-27 15:32:29 -07004542 nextAudioPortGeneration();
4543
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004544 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004545 if (index >= 0) {
4546 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004547 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004548 mAudioPatches.removeItemsAt(index);
4549 mpClientInterface->onAudioPatchListUpdate();
4550 }
4551
Eric Laurentfe231122017-11-17 17:48:06 -08004552 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004553
François Gaffie53615e22015-03-19 09:24:12 +01004554 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004555 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004556
4557 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4558 // no direct outputs are open.
4559 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4560 bool directOutputOpen = false;
4561 for (size_t i = 0; i < mOutputs.size(); i++) {
4562 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4563 directOutputOpen = true;
4564 break;
4565 }
4566 }
4567 if (!directOutputOpen) {
4568 ALOGV("no direct outputs open, reset MSD patch");
4569 setMsdPatch();
4570 }
4571 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004572}
4573
4574void AudioPolicyManager::closeInput(audio_io_handle_t input)
4575{
4576 ALOGV("closeInput(%d)", input);
4577
4578 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4579 if (inputDesc == NULL) {
4580 ALOGW("closeInput() unknown input %d", input);
4581 return;
4582 }
4583
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004585
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004586 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004587 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004588 if (index >= 0) {
4589 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004590 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004591 mAudioPatches.removeItemsAt(index);
4592 mpClientInterface->onAudioPatchListUpdate();
4593 }
4594
Eric Laurentfe231122017-11-17 17:48:06 -08004595 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004596 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004597
4598 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4599 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4600 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4601 SoundTrigger::setCaptureState(false);
4602 }
Eric Laurente552edb2014-03-10 17:42:56 -07004603}
4604
Eric Laurentc75307b2015-03-17 15:29:32 -07004605SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4606 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004607 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004608{
4609 SortedVector<audio_io_handle_t> outputs;
4610
4611 ALOGVV("getOutputsForDevice() device %04x", device);
4612 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004613 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004614 i, openOutputs.valueAt(i)->isDuplicated(),
4615 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004616 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4617 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4618 outputs.add(openOutputs.keyAt(i));
4619 }
4620 }
4621 return outputs;
4622}
4623
Mikhail Naganov37977152018-07-11 15:54:44 -07004624void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4625{
4626 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4627 // output is suspended before any tracks are moved to it
4628 checkA2dpSuspend();
4629 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004630 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004631 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004632 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004633 setMsdPatch();
4634 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004635}
4636
Eric Laurente0720872014-03-11 09:30:41 -07004637void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
4639 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4640 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4641 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4642 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4643
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004644 // also take into account external policy-related changes: add all outputs which are
4645 // associated with policies in the "before" and "after" output vectors
4646 ALOGVV("checkOutputForStrategy(): policy related outputs");
4647 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004648 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004649 if (desc != 0 && desc->mPolicyMix != NULL) {
4650 srcOutputs.add(desc->mIoHandle);
4651 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4652 }
4653 }
4654 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004655 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004656 if (desc != 0 && desc->mPolicyMix != NULL) {
4657 dstOutputs.add(desc->mIoHandle);
4658 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4659 }
4660 }
4661
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004662 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004663 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4664 // audio from invalidated tracks will be rendered when unmuting
4665 uint32_t maxLatency = 0;
4666 for (audio_io_handle_t srcOut : srcOutputs) {
4667 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4668 if (desc != 0 && maxLatency < desc->latency()) {
4669 maxLatency = desc->latency();
4670 }
4671 }
Eric Laurente552edb2014-03-10 17:42:56 -07004672 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4673 strategy, srcOutputs[0], dstOutputs[0]);
4674 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004675 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004676 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4677 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004678 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004679 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004680 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004681 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004682 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004683 if (source != 0){
4684 connectAudioSource(source);
4685 }
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
4687
4688 // Move effects associated to this strategy from previous output to new output
4689 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004690 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004691 }
4692 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004693 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004694 if (getStrategy((audio_stream_type_t)i) == strategy) {
4695 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004696 }
4697 }
4698 }
4699}
4700
Eric Laurente0720872014-03-11 09:30:41 -07004701void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004702{
François Gaffie2110e042015-03-24 08:41:51 +01004703 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004704 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004705 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004706 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004707 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004708 checkOutputForStrategy(STRATEGY_SONIFICATION);
4709 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004710 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004711 checkOutputForStrategy(STRATEGY_MEDIA);
4712 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004713 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004714}
4715
Eric Laurente0720872014-03-11 09:30:41 -07004716void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004717{
François Gaffie53615e22015-03-19 09:24:12 +01004718 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004719 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004720 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004721 return;
4722 }
4723
Eric Laurent3a4311c2014-03-17 12:00:47 -07004724 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004725 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4726 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4727 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004728
4729 // if suspended, restore A2DP output if:
4730 // ((SCO device is NOT connected) ||
4731 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4732 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004733 //
Eric Laurentf732e072016-08-03 19:30:28 -07004734 // if not suspended, suspend A2DP output if:
4735 // (SCO device is connected) &&
4736 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4737 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004738 //
4739 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004740 if (!isScoConnected ||
4741 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4742 AUDIO_POLICY_FORCE_BT_SCO) &&
4743 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4744 AUDIO_POLICY_FORCE_BT_SCO) &&
4745 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004746 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004747
4748 mpClientInterface->restoreOutput(a2dpOutput);
4749 mA2dpSuspended = false;
4750 }
4751 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004752 if (isScoConnected &&
4753 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4754 AUDIO_POLICY_FORCE_BT_SCO) ||
4755 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4756 AUDIO_POLICY_FORCE_BT_SCO) ||
4757 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004758 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004759
4760 mpClientInterface->suspendOutput(a2dpOutput);
4761 mA2dpSuspended = true;
4762 }
4763 }
4764}
4765
Eric Laurent97ac8712018-07-27 18:59:02 -07004766template <class IoDescriptor, class Filter>
4767sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4768 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4769{
4770 auto activeClients = desc->clientsList(true /*activeOnly*/);
4771 auto activeClientsWithRoute =
4772 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4773 active = activeClients.size() > 0;
4774 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4775 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4776 }
4777 return nullptr;
4778}
4779
4780template <class IoCollection, class Filter>
4781sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4782 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4783{
4784 sp<DeviceDescriptor> device;
4785 for (size_t i = 0; i < ioCollection.size(); i++) {
4786 auto desc = ioCollection.valueAt(i);
4787 bool active;
4788 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4789 if (active && curDevice == nullptr) {
4790 return nullptr;
4791 } else if (curDevice != nullptr) {
4792 device = curDevice;
4793 }
4794 }
4795 return device;
4796}
4797
Eric Laurentc75307b2015-03-17 15:29:32 -07004798audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4799 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004800{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004801 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 if (index >= 0) {
4803 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4804 if (patchDesc->mUid != mUidCached) {
4805 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004806 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 return outputDesc->device();
4808 }
4809 }
4810
Eric Laurent97ac8712018-07-27 18:59:02 -07004811 // Honor explicit routing requests only if no client using default routing is active on this
4812 // input: a specific app can not force routing for other apps by setting a preferred device.
4813 bool active; // unused
4814 sp<DeviceDescriptor> deviceDesc =
4815 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4816 if (deviceDesc != nullptr) {
4817 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004818 }
4819
Eric Laurente552edb2014-03-10 17:42:56 -07004820 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004821 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004822 // use device for strategy enforced audible
4823 // 2: we are in call or the strategy phone is active on the output:
4824 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004825 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004826 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004827 // 4: the strategy for enforced audible is active but not enforced on the output:
4828 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004829 // 5: the strategy accessibility is active on the output:
4830 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004831 // 6: the strategy "respectful" sonification is active on the output:
4832 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004833 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004834 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004835 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004836 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004837 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004838 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004839
4840 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4841 // with a refined rule considering mutually exclusive devices (using same backend)
4842 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004843 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004844 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004845 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004846 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4847 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004848 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004849 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004850 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004851 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004852 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4853 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004854 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4855 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004856 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004857 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004858 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004859 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004860 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004861 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004862 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004863 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004864 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004865 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004866 }
4867
Eric Laurent1c333e22014-05-20 10:48:17 -07004868 ALOGV("getNewOutputDevice() selected device %x", device);
4869 return device;
4870}
4871
Eric Laurentfb66dd92016-01-28 18:32:03 -08004872audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004873{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004874 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004875
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004876 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 if (index >= 0) {
4878 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4879 if (patchDesc->mUid != mUidCached) {
4880 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004881 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 return inputDesc->mDevice;
4883 }
4884 }
4885
Eric Laurent97ac8712018-07-27 18:59:02 -07004886 // Honor explicit routing requests only if no client using default routing is active on this
4887 // input: a specific app can not force routing for other apps by setting a preferred device.
4888 bool active;
4889 sp<DeviceDescriptor> deviceDesc =
4890 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4891 if (deviceDesc != nullptr) {
4892 return deviceDesc->type();
4893 }
4894
Eric Laurentdc95a252018-04-12 12:46:56 -07004895 // If we are not in call and no client is active on this input, this methods returns
4896 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004897 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004898 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4899 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4900 }
4901 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004902 device = getDeviceAndMixForInputSource(source);
4903 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004904
Eric Laurente552edb2014-03-10 17:42:56 -07004905 return device;
4906}
4907
Eric Laurent794fde22016-03-11 09:50:45 -08004908bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4909 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004910 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004911}
4912
Eric Laurente0720872014-03-11 09:30:41 -07004913uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004914 return (uint32_t)getStrategy(stream);
4915}
4916
Eric Laurente0720872014-03-11 09:30:41 -07004917audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004918 // By checking the range of stream before calling getStrategy, we avoid
4919 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4920 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004921 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 return AUDIO_DEVICE_NONE;
4923 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004924 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004925 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004926 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4927 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004928 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 }
Eric Laurent794fde22016-03-11 09:50:45 -08004930 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004931 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004932 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004933 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004934 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4935 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004936 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004937 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004938 }
4939 }
Eric Laurente552edb2014-03-10 17:42:56 -07004940 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004941
Eric Laurentb0688d62018-08-14 15:49:18 -07004942 // Favor devices selected on active streams if any to report correct device in case of
4943 // explicit device selection
4944 if (activeDevices != AUDIO_DEVICE_NONE) {
4945 devices = activeDevices;
4946 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004947 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4948 and doesn't really need to.*/
4949 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4950 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4951 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4952 }
Eric Laurente552edb2014-03-10 17:42:56 -07004953 return devices;
4954}
4955
François Gaffie2110e042015-03-24 08:41:51 +01004956routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4957{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004958 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004959 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004960}
4961
Eric Laurent97ac8712018-07-27 18:59:02 -07004962routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004963 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004964 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004965 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004966 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004967 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004968 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004969 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004970 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004971 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004972}
4973
Eric Laurente0720872014-03-11 09:30:41 -07004974void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004975 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004976 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004977 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4978 updateDevicesAndOutputs();
4979 break;
4980 default:
4981 break;
4982 }
4983}
4984
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004985uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004986
4987 // skip beacon mute management if a dedicated TTS output is available
4988 if (mTtsOutputAvailable) {
4989 return 0;
4990 }
4991
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004992 switch(event) {
4993 case STARTING_OUTPUT:
4994 mBeaconMuteRefCount++;
4995 break;
4996 case STOPPING_OUTPUT:
4997 if (mBeaconMuteRefCount > 0) {
4998 mBeaconMuteRefCount--;
4999 }
5000 break;
5001 case STARTING_BEACON:
5002 mBeaconPlayingRefCount++;
5003 break;
5004 case STOPPING_BEACON:
5005 if (mBeaconPlayingRefCount > 0) {
5006 mBeaconPlayingRefCount--;
5007 }
5008 break;
5009 }
5010
5011 if (mBeaconMuteRefCount > 0) {
5012 // any playback causes beacon to be muted
5013 return setBeaconMute(true);
5014 } else {
5015 // no other playback: unmute when beacon starts playing, mute when it stops
5016 return setBeaconMute(mBeaconPlayingRefCount == 0);
5017 }
5018}
5019
5020uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5021 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5022 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5023 // keep track of muted state to avoid repeating mute/unmute operations
5024 if (mBeaconMuted != mute) {
5025 // mute/unmute AUDIO_STREAM_TTS on all outputs
5026 ALOGV("\t muting %d", mute);
5027 uint32_t maxLatency = 0;
5028 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005029 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005030 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005031 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005032 0 /*delay*/, AUDIO_DEVICE_NONE);
5033 const uint32_t latency = desc->latency() * 2;
5034 if (latency > maxLatency) {
5035 maxLatency = latency;
5036 }
5037 }
5038 mBeaconMuted = mute;
5039 return maxLatency;
5040 }
5041 return 0;
5042}
5043
Eric Laurente0720872014-03-11 09:30:41 -07005044audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005045 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005046{
Eric Laurent97ac8712018-07-27 18:59:02 -07005047 // Honor explicit routing requests only if all active clients have a preferred route in which
5048 // case the last active client route is used
5049 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5050 if (deviceDesc != nullptr) {
5051 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005052 }
5053
Eric Laurente552edb2014-03-10 17:42:56 -07005054 if (fromCache) {
5055 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5056 strategy, mDeviceForStrategy[strategy]);
5057 return mDeviceForStrategy[strategy];
5058 }
François Gaffie2110e042015-03-24 08:41:51 +01005059 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005060}
5061
Eric Laurente0720872014-03-11 09:30:41 -07005062void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005063{
5064 for (int i = 0; i < NUM_STRATEGIES; i++) {
5065 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5066 }
5067 mPreviousOutputs = mOutputs;
5068}
5069
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005070uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005071 audio_devices_t prevDevice,
5072 uint32_t delayMs)
5073{
5074 // mute/unmute strategies using an incompatible device combination
5075 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5076 // if unmuting, unmute only after the specified delay
5077 if (outputDesc->isDuplicated()) {
5078 return 0;
5079 }
5080
5081 uint32_t muteWaitMs = 0;
5082 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005083 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005084
5085 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5086 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005087 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005088 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5089 bool doMute = false;
5090
5091 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5092 doMute = true;
5093 outputDesc->mStrategyMutedByDevice[i] = true;
5094 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5095 doMute = true;
5096 outputDesc->mStrategyMutedByDevice[i] = false;
5097 }
Eric Laurent99401132014-05-07 19:48:15 -07005098 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005099 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005100 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005101 // skip output if it does not share any device with current output
5102 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5103 == AUDIO_DEVICE_NONE) {
5104 continue;
5105 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005106 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005107 mute ? "muting" : "unmuting", i, curDevice);
5108 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005109 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005110 if (mute) {
5111 // FIXME: should not need to double latency if volume could be applied
5112 // immediately by the audioflinger mixer. We must account for the delay
5113 // between now and the next time the audioflinger thread for this output
5114 // will process a buffer (which corresponds to one buffer size,
5115 // usually 1/2 or 1/4 of the latency).
5116 if (muteWaitMs < desc->latency() * 2) {
5117 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005118 }
5119 }
5120 }
5121 }
5122 }
5123 }
5124
Eric Laurent99401132014-05-07 19:48:15 -07005125 // temporary mute output if device selection changes to avoid volume bursts due to
5126 // different per device volumes
5127 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005128 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5129 // temporary mute duration is conservatively set to 4 times the reported latency
5130 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5131 if (muteWaitMs < tempMuteWaitMs) {
5132 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005133 }
Eric Laurentdc462862016-07-19 12:29:53 -07005134
Eric Laurent99401132014-05-07 19:48:15 -07005135 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005136 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005137 // make sure that we do not start the temporary mute period too early in case of
5138 // delayed device change
5139 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005140 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005141 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005142 }
5143 }
5144 }
5145
Eric Laurente552edb2014-03-10 17:42:56 -07005146 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5147 if (muteWaitMs > delayMs) {
5148 muteWaitMs -= delayMs;
5149 usleep(muteWaitMs * 1000);
5150 return muteWaitMs;
5151 }
5152 return 0;
5153}
5154
Eric Laurentc75307b2015-03-17 15:29:32 -07005155uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005156 audio_devices_t device,
5157 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005158 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005159 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005160 const char *address,
5161 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005162{
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005164 AudioParameter param;
5165 uint32_t muteWaitMs;
5166
5167 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005168 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5169 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5170 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5171 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005172 return muteWaitMs;
5173 }
5174 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5175 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005176 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005177 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005178 return 0;
5179 }
5180
5181 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005182 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005183
5184 audio_devices_t prevDevice = outputDesc->mDevice;
5185
Paul McLeanaa981192015-03-21 09:55:15 -07005186 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005187
5188 if (device != AUDIO_DEVICE_NONE) {
5189 outputDesc->mDevice = device;
5190 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005191
5192 // if the outputs are not materially active, there is no need to mute.
5193 if (requiresMuteCheck) {
5194 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5195 } else {
5196 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5197 muteWaitMs = 0;
5198 }
Eric Laurente552edb2014-03-10 17:42:56 -07005199
5200 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005201 // the requested device is AUDIO_DEVICE_NONE
5202 // OR the requested device is the same as current device
5203 // AND force is not specified
5204 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005205 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005206 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5207 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005208 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005209 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005210 return muteWaitMs;
5211 }
5212
5213 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005214
Eric Laurente552edb2014-03-10 17:42:56 -07005215 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005216 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005218 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005219 DeviceVector deviceList;
5220 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005221 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005222 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005223 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5224 device, String8(address));
5225 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005226 }
5227
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005229 PatchBuilder patchBuilder;
5230 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005231 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005232 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005234 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005235 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005236
5237 // inform all input as well
5238 for (size_t i = 0; i < mInputs.size(); i++) {
5239 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005240 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005241 AudioParameter inputCmd = AudioParameter();
5242 ALOGV("%s: inform input %d of device:%d", __func__,
5243 inputDescriptor->mIoHandle, device);
5244 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5245 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5246 inputCmd.toString(),
5247 delayMs);
5248 }
5249 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005250 }
Eric Laurente552edb2014-03-10 17:42:56 -07005251
5252 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005253 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005254
5255 return muteWaitMs;
5256}
5257
Eric Laurentc75307b2015-03-17 15:29:32 -07005258status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 int delayMs,
5260 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005261{
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 ssize_t index;
5263 if (patchHandle) {
5264 index = mAudioPatches.indexOfKey(*patchHandle);
5265 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005266 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 }
5268 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005269 return INVALID_OPERATION;
5270 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5272 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005273 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005274 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 removeAudioPatch(patchDesc->mHandle);
5276 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005277 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005278 return status;
5279}
5280
5281status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5282 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 bool force,
5284 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005285{
5286 status_t status = NO_ERROR;
5287
Eric Laurent1f2f2232014-06-02 12:01:23 -07005288 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005289 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5290 inputDesc->mDevice = device;
5291
Mikhail Naganov708e0382018-05-30 09:53:04 -07005292 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005293 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005294 PatchBuilder patchBuilder;
5295 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005296 // AUDIO_SOURCE_HOTWORD is for internal use only:
5297 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005298 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5299 auto result = usecase;
5300 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5301 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5302 }
5303 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005304 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005305 addSource(deviceList.itemAt(0));
5306 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 }
5308 }
5309 return status;
5310}
5311
Eric Laurent6a94d692014-05-20 11:18:06 -07005312status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5313 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005314{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005315 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 ssize_t index;
5317 if (patchHandle) {
5318 index = mAudioPatches.indexOfKey(*patchHandle);
5319 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005320 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 }
5322 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005323 return INVALID_OPERATION;
5324 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5326 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005327 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005328 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 removeAudioPatch(patchDesc->mHandle);
5330 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005331 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 return status;
5333}
5334
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005335sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005336 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005337 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005338 audio_format_t& format,
5339 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005340 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005341{
5342 // Choose an input profile based on the requested capture parameters: select the first available
5343 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005344 //
5345 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5346 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005347
Glenn Kasten730b9262018-03-29 15:01:26 -07005348 sp<IOProfile> firstInexact;
5349 uint32_t updatedSamplingRate = 0;
5350 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5351 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005352 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005353 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005354 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005355 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005356 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005357 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005358 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005359 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005360 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005361 &channelMask /*updatedChannelMask*/,
5362 // FIXME ugly cast
5363 (audio_output_flags_t) flags,
5364 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005365 return profile;
5366 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005367 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5368 samplingRate,
5369 &updatedSamplingRate,
5370 format,
5371 &updatedFormat,
5372 channelMask,
5373 &updatedChannelMask,
5374 // FIXME ugly cast
5375 (audio_output_flags_t) flags,
5376 false /*exactMatchRequiredForInputFlags*/)) {
5377 firstInexact = profile;
5378 }
5379
Eric Laurente552edb2014-03-10 17:42:56 -07005380 }
5381 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005382 if (firstInexact != nullptr) {
5383 samplingRate = updatedSamplingRate;
5384 format = updatedFormat;
5385 channelMask = updatedChannelMask;
5386 return firstInexact;
5387 }
Eric Laurente552edb2014-03-10 17:42:56 -07005388 return NULL;
5389}
5390
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005391
5392audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005393 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005394{
Eric Laurent97ac8712018-07-27 18:59:02 -07005395 // Honor explicit routing requests only if all active clients have a preferred route in which
5396 // case the last active client route is used
5397 sp<DeviceDescriptor> deviceDesc =
5398 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5399 if (deviceDesc != nullptr) {
5400 return deviceDesc->type();
5401 }
5402
5403
François Gaffie036e1e92015-03-19 10:16:24 +01005404 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5405 audio_devices_t selectedDeviceFromMix =
5406 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005407
François Gaffie036e1e92015-03-19 10:16:24 +01005408 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5409 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005410 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005411 return getDeviceForInputSource(inputSource);
5412}
5413
5414audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5415{
Eric Laurent97ac8712018-07-27 18:59:02 -07005416 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005417}
5418
Eric Laurente0720872014-03-11 09:30:41 -07005419float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005420 int index,
5421 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005422{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005423 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005424
5425 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5426 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5427 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5428 // the ringtone volume
5429 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5430 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5431 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5432 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5433 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5434 }
5435
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005436 // in-call: always cap volume by voice volume + some low headroom
5437 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005438 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005439 switch (stream) {
5440 case AUDIO_STREAM_SYSTEM:
5441 case AUDIO_STREAM_RING:
5442 case AUDIO_STREAM_MUSIC:
5443 case AUDIO_STREAM_ALARM:
5444 case AUDIO_STREAM_NOTIFICATION:
5445 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5446 case AUDIO_STREAM_DTMF:
5447 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005448 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005449 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005450 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005451 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005452 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005453 if (volumeDB > maxVoiceVolDb) {
5454 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5455 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5456 volumeDB = maxVoiceVolDb;
5457 }
5458 } break;
5459 default:
5460 break;
5461 }
5462 }
5463
Eric Laurente552edb2014-03-10 17:42:56 -07005464 // if a headset is connected, apply the following rules to ring tones and notifications
5465 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005466 // - always attenuate notifications volume by 6dB
5467 // - attenuate ring tones volume by 6dB unless music is not playing and
5468 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005469 // - if music is playing, always limit the volume to current music volume,
5470 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005471 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005472 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5473 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5474 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005475 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005476 AUDIO_DEVICE_OUT_USB_HEADSET |
5477 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005478 ((stream_strategy == STRATEGY_SONIFICATION)
5479 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005480 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005481 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005482 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005483 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005484 // when the phone is ringing we must consider that music could have been paused just before
5485 // by the music application and behave as if music was active if the last music track was
5486 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005487 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005488 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005489 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005490 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005491 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005492 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5493 musicDevice),
5494 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005495 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5496 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005497 if (volumeDB > minVolDB) {
5498 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005499 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005500 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005501 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5502 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5503 // on A2DP, also ensure notification volume is not too low compared to media when
5504 // intended to be played
5505 if ((volumeDB > -96.0f) &&
5506 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5507 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5508 stream, device,
5509 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5510 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5511 }
5512 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005513 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5514 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005515 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005516 }
5517 }
5518
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005519 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005520}
5521
Eric Laurent3839bc02018-07-10 18:33:34 -07005522int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5523 audio_stream_type_t srcStream,
5524 audio_stream_type_t dstStream)
5525{
5526 if (srcStream == dstStream) {
5527 return srcIndex;
5528 }
5529 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5530 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5531 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5532 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5533
5534 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5535}
5536
Eric Laurente0720872014-03-11 09:30:41 -07005537status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005538 int index,
5539 const sp<AudioOutputDescriptor>& outputDesc,
5540 audio_devices_t device,
5541 int delayMs,
5542 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005543{
Eric Laurente552edb2014-03-10 17:42:56 -07005544 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005546 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005547 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005548 return NO_ERROR;
5549 }
François Gaffie2110e042015-03-24 08:41:51 +01005550 audio_policy_forced_cfg_t forceUseForComm =
5551 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005552 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005553 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5554 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005555 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005556 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005557 return INVALID_OPERATION;
5558 }
5559
Eric Laurentc75307b2015-03-17 15:29:32 -07005560 if (device == AUDIO_DEVICE_NONE) {
5561 device = outputDesc->device();
5562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005563
Eric Laurentffbc80f2015-03-18 18:30:19 -07005564 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005565 if (outputDesc->isFixedVolume(device) ||
5566 // Force VoIP volume to max for bluetooth SCO
5567 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5568 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005569 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005570 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005571
Eric Laurentffbc80f2015-03-18 18:30:19 -07005572 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005573
Eric Laurent3b73df72014-03-11 09:06:29 -07005574 if (stream == AUDIO_STREAM_VOICE_CALL ||
5575 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005576 float voiceVolume;
5577 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005578 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005579 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005580 } else {
5581 voiceVolume = 1.0;
5582 }
5583
Eric Laurent18fba842016-03-31 14:41:26 -07005584 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005585 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5586 mLastVoiceVolume = voiceVolume;
5587 }
5588 }
5589
5590 return NO_ERROR;
5591}
5592
Eric Laurentc75307b2015-03-17 15:29:32 -07005593void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5594 audio_devices_t device,
5595 int delayMs,
5596 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005597{
Eric Laurentc75307b2015-03-17 15:29:32 -07005598 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005599
Eric Laurent794fde22016-03-11 09:50:45 -08005600 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005601 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005602 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005603 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005604 device,
5605 delayMs,
5606 force);
5607 }
5608}
5609
Eric Laurente0720872014-03-11 09:30:41 -07005610void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 bool on,
5612 const sp<AudioOutputDescriptor>& outputDesc,
5613 int delayMs,
5614 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005615{
Eric Laurent72249d52015-06-08 11:12:15 -07005616 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5617 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005618 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005619 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005620 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005621 }
5622 }
5623}
5624
Eric Laurente0720872014-03-11 09:30:41 -07005625void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005626 bool on,
5627 const sp<AudioOutputDescriptor>& outputDesc,
5628 int delayMs,
5629 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005630{
Eric Laurente552edb2014-03-10 17:42:56 -07005631 if (device == AUDIO_DEVICE_NONE) {
5632 device = outputDesc->device();
5633 }
5634
Eric Laurentc75307b2015-03-17 15:29:32 -07005635 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5636 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005637
5638 if (on) {
5639 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005640 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005641 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005642 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005643 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005644 }
5645 }
5646 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5647 outputDesc->mMuteCount[stream]++;
5648 } else {
5649 if (outputDesc->mMuteCount[stream] == 0) {
5650 ALOGV("setStreamMute() unmuting non muted stream!");
5651 return;
5652 }
5653 if (--outputDesc->mMuteCount[stream] == 0) {
5654 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005655 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005656 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005657 device,
5658 delayMs);
5659 }
5660 }
5661}
5662
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005663audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5664{
5665 // flags to stream type mapping
5666 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5667 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5668 }
5669 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5670 return AUDIO_STREAM_BLUETOOTH_SCO;
5671 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005672 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5673 return AUDIO_STREAM_TTS;
5674 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005675
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005676 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005677}
Eric Laurente83b55d2014-11-14 10:06:21 -08005678
François Gaffie53615e22015-03-19 09:24:12 +01005679bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5680{
Eric Laurente83b55d2014-11-14 10:06:21 -08005681 // has flags that map to a strategy?
5682 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5683 return true;
5684 }
5685
5686 // has known usage?
5687 switch (paa->usage) {
5688 case AUDIO_USAGE_UNKNOWN:
5689 case AUDIO_USAGE_MEDIA:
5690 case AUDIO_USAGE_VOICE_COMMUNICATION:
5691 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5692 case AUDIO_USAGE_ALARM:
5693 case AUDIO_USAGE_NOTIFICATION:
5694 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5695 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5696 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5697 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5698 case AUDIO_USAGE_NOTIFICATION_EVENT:
5699 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5700 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5701 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5702 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005703 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005704 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005705 break;
5706 default:
5707 return false;
5708 }
5709 return true;
5710}
5711
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005712bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005713 routing_strategy strategy, uint32_t inPastMs,
5714 nsecs_t sysTime) const
5715{
5716 if ((sysTime == 0) && (inPastMs != 0)) {
5717 sysTime = systemTime();
5718 }
Eric Laurent794fde22016-03-11 09:50:45 -08005719 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005720 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005721 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005722 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5723 return true;
5724 }
5725 }
5726 return false;
5727}
5728
Eric Laurent484e9272018-06-07 17:29:23 -07005729bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5730 routing_strategy strategy, uint32_t inPastMs,
5731 nsecs_t sysTime) const
5732{
5733 for (size_t i = 0; i < mOutputs.size(); i++) {
5734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5735 if (outputDesc->sharesHwModuleWith(desc)
5736 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5737 return true;
5738 }
5739 }
5740 return false;
5741}
5742
François Gaffie2110e042015-03-24 08:41:51 +01005743audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5744{
5745 return mEngine->getForceUse(usage);
5746}
5747
5748bool AudioPolicyManager::isInCall()
5749{
5750 return isStateInCall(mEngine->getPhoneState());
5751}
5752
5753bool AudioPolicyManager::isStateInCall(int state)
5754{
5755 return is_state_in_call(state);
5756}
5757
Eric Laurentd60560a2015-04-10 11:31:20 -07005758void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5759{
5760 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005761 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5762 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5763 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5764 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005765 }
5766 }
5767
5768 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5769 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5770 bool release = false;
5771 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5772 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5773 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5774 source->ext.device.type == deviceDesc->type()) {
5775 release = true;
5776 }
5777 }
5778 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5779 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5780 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5781 sink->ext.device.type == deviceDesc->type()) {
5782 release = true;
5783 }
5784 }
5785 if (release) {
5786 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5787 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5788 }
5789 }
5790}
5791
Phil Burk09bc4612016-02-24 15:58:15 -08005792// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005793void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5794 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005795 // TODO Set this based on Config properties.
5796 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005797
5798 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5799 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005800 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005801
jiabin81772902018-04-02 17:52:27 -07005802 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5803 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5804 formats.clear();
5805 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5806 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005807 }
jiabin81772902018-04-02 17:52:27 -07005808 // Always enable IEC61937 when in MANUAL mode.
5809 formats.add(AUDIO_FORMAT_IEC61937);
5810 } else { // NEVER, AUTO or ALWAYS
5811 // Analyze original support for various formats.
5812 bool supportsAC3 = false;
5813 bool supportsOtherSurround = false;
5814 bool supportsIEC61937 = false;
5815 mSurroundFormats.clear();
5816 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5817 audio_format_t format = formats[formatIndex];
5818 switch (format) {
5819 case AUDIO_FORMAT_AC3:
5820 supportsAC3 = true;
5821 break;
5822 case AUDIO_FORMAT_E_AC3:
5823 case AUDIO_FORMAT_DTS:
5824 case AUDIO_FORMAT_DTS_HD:
5825 // If ALWAYS, remove all other surround formats here
5826 // since we will add them later.
5827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5828 formats.removeAt(formatIndex);
5829 formatIndex--;
5830 }
5831 supportsOtherSurround = true;
5832 break;
5833 case AUDIO_FORMAT_IEC61937:
5834 supportsIEC61937 = true;
5835 break;
5836 default:
5837 break;
5838 }
5839 }
Phil Burk09bc4612016-02-24 15:58:15 -08005840
jiabin81772902018-04-02 17:52:27 -07005841 // Modify formats based on surround preferences.
5842 // If NEVER, remove support for surround formats.
5843 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5844 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5845 // Remove surround sound related formats.
5846 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5847 audio_format_t format = formats[formatIndex];
5848 switch(format) {
5849 case AUDIO_FORMAT_AC3:
5850 case AUDIO_FORMAT_E_AC3:
5851 case AUDIO_FORMAT_DTS:
5852 case AUDIO_FORMAT_DTS_HD:
5853 case AUDIO_FORMAT_IEC61937:
5854 formats.removeAt(formatIndex);
5855 break;
5856 default:
5857 formatIndex++; // keep it
5858 break;
5859 }
5860 }
5861 supportsAC3 = false;
5862 supportsOtherSurround = false;
5863 supportsIEC61937 = false;
5864 }
5865 } else { // AUTO or ALWAYS
5866 // Most TVs support AC3 even if they do not report it in the EDID.
5867 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5868 && !supportsAC3) {
5869 formats.add(AUDIO_FORMAT_AC3);
5870 supportsAC3 = true;
5871 }
5872
5873 // If ALWAYS, add support for raw surround formats if all are missing.
5874 // This assumes that if any of these formats are reported by the HAL
5875 // then the report is valid and should not be modified.
5876 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5877 formats.add(AUDIO_FORMAT_E_AC3);
5878 formats.add(AUDIO_FORMAT_DTS);
5879 formats.add(AUDIO_FORMAT_DTS_HD);
5880 supportsOtherSurround = true;
5881 }
5882
5883 // Add support for IEC61937 if any raw surround supported.
5884 // The HAL could do this but add it here, just in case.
5885 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5886 formats.add(AUDIO_FORMAT_IEC61937);
5887 supportsIEC61937 = true;
5888 }
5889
5890 // Add reported surround sound formats to enabled surround formats.
5891 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005892 audio_format_t format = formats[formatIndex];
5893 switch(format) {
5894 case AUDIO_FORMAT_AC3:
5895 case AUDIO_FORMAT_E_AC3:
5896 case AUDIO_FORMAT_DTS:
5897 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005898 case AUDIO_FORMAT_AAC_LC:
5899 case AUDIO_FORMAT_DOLBY_TRUEHD:
5900 case AUDIO_FORMAT_E_AC3_JOC:
5901 mSurroundFormats.insert(format);
Andy Hung320fd852018-10-09 14:06:37 -07005902 break;
Phil Burk07ac1142016-03-25 13:39:29 -07005903 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005904 break;
5905 }
Phil Burk09bc4612016-02-24 15:58:15 -08005906 }
Phil Burk07ac1142016-03-25 13:39:29 -07005907 }
Phil Burk09bc4612016-02-24 15:58:15 -08005908 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005909}
5910
5911// Modify the list of channel masks supported.
5912void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5913 ChannelsVector &channelMasks = *channelMasksPtr;
5914 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5915 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5916
5917 // If NEVER, then remove support for channelMasks > stereo.
5918 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5919 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5920 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5921 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5922 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5923 channelMasks.removeAt(maskIndex);
5924 } else {
5925 maskIndex++;
5926 }
5927 }
jiabin81772902018-04-02 17:52:27 -07005928 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5929 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5930 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005931 bool supports5dot1 = false;
5932 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005933 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005934 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5935 supports5dot1 = true;
5936 break;
5937 }
5938 }
5939 // If not then add 5.1 support.
5940 if (!supports5dot1) {
5941 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5942 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5943 }
Phil Burk09bc4612016-02-24 15:58:15 -08005944 }
5945}
5946
Phil Burk00eeb322016-03-31 12:41:00 -07005947void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5948 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005949 AudioProfileVector &profiles)
5950{
5951 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005952
François Gaffie112b0af2015-11-19 16:13:25 +01005953 // Format MUST be checked first to update the list of AudioProfile
5954 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005955 reply = mpClientInterface->getParameters(
5956 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005957 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005958 AudioParameter repliedParameters(reply);
5959 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005960 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005961 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5962 return;
5963 }
Phil Burk09bc4612016-02-24 15:58:15 -08005964 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005965 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005966 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005967 }
Phil Burk09bc4612016-02-24 15:58:15 -08005968 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005969 }
François Gaffie112b0af2015-11-19 16:13:25 +01005970
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005971 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005972 ChannelsVector channelMasks;
5973 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005974 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005975 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005976
5977 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005978 reply = mpClientInterface->getParameters(
5979 ioHandle,
5980 requestedParameters.toString() + ";" +
5981 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005982 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005983 AudioParameter repliedParameters(reply);
5984 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005985 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005986 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005987 }
5988 }
5989 if (profiles.hasDynamicChannelsFor(format)) {
5990 reply = mpClientInterface->getParameters(ioHandle,
5991 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005992 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005993 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005994 AudioParameter repliedParameters(reply);
5995 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005996 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005997 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005998 if (device == AUDIO_DEVICE_OUT_HDMI) {
5999 filterSurroundChannelMasks(&channelMasks);
6000 }
François Gaffie112b0af2015-11-19 16:13:25 +01006001 }
6002 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006003 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006004 }
6005}
Eric Laurentd60560a2015-04-10 11:31:20 -07006006
Mikhail Naganovdc769682018-05-04 15:34:08 -07006007status_t AudioPolicyManager::installPatch(const char *caller,
6008 audio_patch_handle_t *patchHandle,
6009 AudioIODescriptorInterface *ioDescriptor,
6010 const struct audio_patch *patch,
6011 int delayMs)
6012{
6013 ssize_t index = mAudioPatches.indexOfKey(
6014 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6015 *patchHandle : ioDescriptor->getPatchHandle());
6016 sp<AudioPatch> patchDesc;
6017 status_t status = installPatch(
6018 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6019 if (status == NO_ERROR) {
6020 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6021 }
6022 return status;
6023}
6024
6025status_t AudioPolicyManager::installPatch(const char *caller,
6026 ssize_t index,
6027 audio_patch_handle_t *patchHandle,
6028 const struct audio_patch *patch,
6029 int delayMs,
6030 uid_t uid,
6031 sp<AudioPatch> *patchDescPtr)
6032{
6033 sp<AudioPatch> patchDesc;
6034 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6035 if (index >= 0) {
6036 patchDesc = mAudioPatches.valueAt(index);
6037 afPatchHandle = patchDesc->mAfPatchHandle;
6038 }
6039
6040 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6041 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6042 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6043 if (status == NO_ERROR) {
6044 if (index < 0) {
6045 patchDesc = new AudioPatch(patch, uid);
6046 addAudioPatch(patchDesc->mHandle, patchDesc);
6047 } else {
6048 patchDesc->mPatch = *patch;
6049 }
6050 patchDesc->mAfPatchHandle = afPatchHandle;
6051 if (patchHandle) {
6052 *patchHandle = patchDesc->mHandle;
6053 }
6054 nextAudioPortGeneration();
6055 mpClientInterface->onAudioPatchListUpdate();
6056 }
6057 if (patchDescPtr) *patchDescPtr = patchDesc;
6058 return status;
6059}
6060
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006061} // namespace android