blob: e28ab68575a27ee8c61826de41ed6b4a6ae3500a [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110034#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070035
François Gaffie2110e042015-03-24 08:41:51 +010036#include <AudioPolicyManagerInterface.h>
37#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070040#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080041#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
Mikhail Naganov15be9d22017-11-08 14:18:13 +110065// Compressed formats for MSD module, ordered from most preferred to least preferred.
66static const std::vector<audio_format_t> compressedFormatsOrder = {{
67 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
68 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
69// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
70static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
71 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
72 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
73 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
74
Eric Laurente552edb2014-03-10 17:42:56 -070075// ----------------------------------------------------------------------------
76// AudioPolicyInterface implementation
77// ----------------------------------------------------------------------------
78
Eric Laurente0720872014-03-11 09:30:41 -070079status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080080 audio_policy_dev_state_t state,
81 const char *device_address,
82 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070083{
jiabina7b43792018-02-15 16:04:46 -080084 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
85 nextAudioPortGeneration();
86 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080087}
88
François Gaffie44481e72016-04-20 07:49:57 +020089void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
90 audio_policy_dev_state_t state,
91 const String8 &device_address)
92{
93 AudioParameter param(device_address);
94 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070095 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020096 param.addInt(key, device);
97 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
98}
99
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800101 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800102 const char *device_address,
103 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800104{
Paul McLeane743a472015-01-28 11:07:31 -0800105 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800106 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700107
108 // connect/disconnect only 1 device at a time
109 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
110
François Gaffie53615e22015-03-19 09:24:12 +0100111 sp<DeviceDescriptor> devDesc =
112 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800113
Eric Laurente552edb2014-03-10 17:42:56 -0700114 // handle output devices
115 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700116 SortedVector <audio_io_handle_t> outputs;
117
Eric Laurent3a4311c2014-03-17 12:00:47 -0700118 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
119
Eric Laurente552edb2014-03-10 17:42:56 -0700120 // save a copy of the opened output descriptors before any output is opened or closed
121 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
122 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700123 switch (state)
124 {
125 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800126 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700128 ALOGW("setDeviceConnectionState() device already connected: %x", device);
129 return INVALID_OPERATION;
130 }
131 ALOGV("setDeviceConnectionState() connecting device %x", device);
132
Eric Laurente552edb2014-03-10 17:42:56 -0700133 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700134 index = mAvailableOutputDevices.add(devDesc);
135 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100136 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700137 if (module == 0) {
138 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
139 device);
140 mAvailableOutputDevices.remove(devDesc);
141 return INVALID_OPERATION;
142 }
Paul McLeane743a472015-01-28 11:07:31 -0800143 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 } else {
145 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700146 }
147
François Gaffie44481e72016-04-20 07:49:57 +0200148 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
149 // parameters on newly connected devices (instead of opening the outputs...)
150 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
151
Eric Laurenta1d525f2015-01-29 13:36:45 -0800152 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700153 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200154
155 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
156 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700157 return INVALID_OPERATION;
158 }
François Gaffie2110e042015-03-24 08:41:51 +0100159 // Propagate device availability to Engine
160 mEngine->setDeviceConnectionState(devDesc, state);
161
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700162 // outputs should never be empty here
163 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
164 "checkOutputsForDevice() returned no outputs but status OK");
165 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
166 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800167
Eric Laurent3ae5f312015-02-03 17:12:08 -0800168 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700169 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700170 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700171 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700172 ALOGW("setDeviceConnectionState() device not connected: %x", device);
173 return INVALID_OPERATION;
174 }
175
Paul McLean5c477aa2014-08-20 16:47:57 -0700176 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
177
Paul McLeane743a472015-01-28 11:07:31 -0800178 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200179 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700180
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700182 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700183
Eric Laurenta1d525f2015-01-29 13:36:45 -0800184 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100185
186 // Propagate device availability to Engine
187 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700188 } break;
189
190 default:
191 ALOGE("setDeviceConnectionState() invalid state: %x", state);
192 return BAD_VALUE;
193 }
194
Mikhail Naganov37977152018-07-11 15:54:44 -0700195 checkForDeviceAndOutputChanges([&]() {
196 // outputs must be closed after checkOutputForAllStrategies() is executed
197 if (!outputs.isEmpty()) {
198 for (audio_io_handle_t output : outputs) {
199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
200 // close unused outputs after device disconnection or direct outputs that have been
201 // opened by checkOutputsForDevice() to query dynamic parameters
202 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
203 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
204 (desc->mDirectOpenCount == 0))) {
205 closeOutput(output);
206 }
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700208 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
209 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700211 return false;
212 });
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurent87ffa392015-05-22 10:32:38 -0700214 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700215 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
216 updateCallRouting(newDevice);
217 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100218 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700219 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700220 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
221 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
222 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700223 // do not force device change on duplicated output because if device is 0, it will
224 // also force a device 0 for the two outputs it is duplicated to which may override
225 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100226 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
227 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100228 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700229 // always force when disconnecting (a non-duplicated device)
230 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700231 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 }
Eric Laurente552edb2014-03-10 17:42:56 -0700233 }
234
Eric Laurentd60560a2015-04-10 11:31:20 -0700235 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
236 cleanUpForDevice(devDesc);
237 }
238
Eric Laurent72aa32f2014-05-30 18:51:48 -0700239 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700240 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700241 } // end if is output device
242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // handle input devices
244 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700245 SortedVector <audio_io_handle_t> inputs;
246
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700248 switch (state)
249 {
250 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700251 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700253 ALOGW("setDeviceConnectionState() device already connected: %d", device);
254 return INVALID_OPERATION;
255 }
François Gaffie53615e22015-03-19 09:24:12 +0100256 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700257 if (module == NULL) {
258 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
259 device);
260 return INVALID_OPERATION;
261 }
François Gaffie44481e72016-04-20 07:49:57 +0200262
263 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
264 // parameters on newly connected devices (instead of opening the inputs...)
265 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
266
Paul McLean9080a4c2015-06-18 08:24:02 -0700267 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200268 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
269 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700270 return INVALID_OPERATION;
271 }
272
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 index = mAvailableInputDevices.add(devDesc);
274 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800275 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 } else {
277 return NO_MEMORY;
278 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800279
François Gaffie2110e042015-03-24 08:41:51 +0100280 // Propagate device availability to Engine
281 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700282 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700283
284 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700285 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700287 ALOGW("setDeviceConnectionState() device not connected: %d", device);
288 return INVALID_OPERATION;
289 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700290
291 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
292
293 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200294 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700295
Paul McLean9080a4c2015-06-18 08:24:02 -0700296 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700297 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
François Gaffie2110e042015-03-24 08:41:51 +0100299 // Propagate device availability to Engine
300 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700301 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700302
303 default:
304 ALOGE("setDeviceConnectionState() invalid state: %x", state);
305 return BAD_VALUE;
306 }
307
Eric Laurentd4692962014-05-05 18:13:44 -0700308 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700309 // As the input device list can impact the output device selection, update
310 // getDeviceForStrategy() cache
311 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700312
Eric Laurent87ffa392015-05-22 10:32:38 -0700313 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700314 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
315 updateCallRouting(newDevice);
316 }
317
Eric Laurentd60560a2015-04-10 11:31:20 -0700318 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
319 cleanUpForDevice(devDesc);
320 }
321
Eric Laurentb52c1522014-05-20 11:27:36 -0700322 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700323 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700324 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700325
326 ALOGW("setDeviceConnectionState() invalid device: %x", device);
327 return BAD_VALUE;
328}
329
Eric Laurente0720872014-03-11 09:30:41 -0700330audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100331 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700332{
Eric Laurent634b7142016-04-20 13:48:02 -0700333 sp<DeviceDescriptor> devDesc =
334 mHwModules.getDeviceDescriptor(device, device_address, "",
335 (strlen(device_address) != 0)/*matchAddress*/);
336
337 if (devDesc == 0) {
338 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
339 device, device_address);
340 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
341 }
François Gaffie53615e22015-03-19 09:24:12 +0100342
Eric Laurent3a4311c2014-03-17 12:00:47 -0700343 DeviceVector *deviceVector;
344
Eric Laurente552edb2014-03-10 17:42:56 -0700345 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700347 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 deviceVector = &mAvailableInputDevices;
349 } else {
350 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
351 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700352 }
Eric Laurent634b7142016-04-20 13:48:02 -0700353
354 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
355 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800356}
357
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800358status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
359 const char *device_address,
360 const char *device_name)
361{
362 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700363 String8 reply;
364 AudioParameter param;
365 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366
367 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
368 device, device_address, device_name);
369
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800370 // connect/disconnect only 1 device at a time
371 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
372
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800373 // Check if the device is currently connected
374 sp<DeviceDescriptor> devDesc =
375 mHwModules.getDeviceDescriptor(device, device_address, device_name);
376 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
377 if (index < 0) {
378 // Nothing to do: device is not connected
379 return NO_ERROR;
380 }
381
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700382 // For offloaded A2DP, Hw modules may have the capability to
383 // configure codecs. Check if any of the loaded hw modules
384 // supports this.
385 // If supported, send a set parameter to configure A2DP codecs
386 // and return. No need to toggle device state.
387 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
388 reply = mpClientInterface->getParameters(
389 AUDIO_IO_HANDLE_NONE,
390 String8(AudioParameter::keyReconfigA2dpSupported));
391 AudioParameter repliedParameters(reply);
392 repliedParameters.getInt(
393 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
394 if (isReconfigA2dpSupported) {
395 const String8 key(AudioParameter::keyReconfigA2dp);
396 param.add(key, String8("true"));
397 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
398 return NO_ERROR;
399 }
400 }
401
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800402 // Toggle the device state: UNAVAILABLE -> AVAILABLE
403 // This will force reading again the device configuration
404 status = setDeviceConnectionState(device,
405 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
406 device_address, device_name);
407 if (status != NO_ERROR) {
408 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
409 status);
410 return status;
411 }
412
413 status = setDeviceConnectionState(device,
414 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
415 device_address, device_name);
416 if (status != NO_ERROR) {
417 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
418 status);
419 return status;
420 }
421
422 return NO_ERROR;
423}
424
Eric Laurentdc462862016-07-19 12:29:53 -0700425uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700426{
427 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700428 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429
Andy Hunga76c7de2016-12-13 19:14:31 -0800430 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700431 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700432 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800433 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
435
436 // release existing RX patch if any
437 if (mCallRxPatch != 0) {
438 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
439 mCallRxPatch.clear();
440 }
441 // release TX patch if any
442 if (mCallTxPatch != 0) {
443 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
444 mCallTxPatch.clear();
445 }
446
447 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
448 // via setOutputDevice() on primary output.
449 // Otherwise, create two audio patches for TX and RX path.
450 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700451 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 // If the TX device is also on the primary HW module, setOutputDevice() will take care
453 // of it due to legacy implementation. If not, create a patch.
454 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
455 == AUDIO_DEVICE_NONE) {
456 createTxPatch = true;
457 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700458 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800459 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 createTxPatch = true;
461 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700462 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800463 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 return muteWaitMs;
467}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
470 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700471 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800473 sp<DeviceDescriptor> txSourceDeviceDesc;
474 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700475 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
476 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
479 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 }
481
482 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
483 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
484 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
485 // request to reuse existing output stream if one is already opened to reach the target device
486 if (output != AUDIO_IO_HANDLE_NONE) {
487 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
488 ALOG_ASSERT(!outputDesc->isDuplicated(),
489 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700490 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800491 }
492
493 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700494 // terminate active capture if on the same HW module as the call TX source device
495 // FIXME: would be better to refine to only inputs whose profile connects to the
496 // call TX device but this information is not in the audio patch and logic here must be
497 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800498 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800499 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700500 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700501 }
502 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700503 }
Eric Laurentdc462862016-07-19 12:29:53 -0700504
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800505 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700506 status_t status = mpClientInterface->createAudioPatch(
507 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 ALOGW_IF(status != NO_ERROR,
509 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
510 sp<AudioPatch> audioPatch;
511 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700512 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 audioPatch->mAfPatchHandle = afPatchHandle;
514 audioPatch->mUid = mUidCached;
515 }
516 return audioPatch;
517}
518
Mikhail Naganovdc769682018-05-04 15:34:08 -0700519sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100520 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700521 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800522 ALOG_ASSERT(!deviceList.isEmpty(),
523 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700524 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700525}
526
Eric Laurente0720872014-03-11 09:30:41 -0700527void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700528{
529 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100530 // store previous phone state for management of sonification strategy below
531 int oldState = mEngine->getPhoneState();
532
533 if (mEngine->setPhoneState(state) != NO_ERROR) {
534 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700535 return;
536 }
François Gaffie2110e042015-03-24 08:41:51 +0100537 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700538 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800541 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
543
François Gaffie2110e042015-03-24 08:41:51 +0100544 /**
545 * Switching to or from incall state or switching between telephony and VoIP lead to force
546 * routing command.
547 */
548 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
549 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700550
551 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700552 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700553
Eric Laurente552edb2014-03-10 17:42:56 -0700554 int delayMs = 0;
555 if (isStateInCall(state)) {
556 nsecs_t sysTime = systemTime();
557 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 // mute media and sonification strategies and delay device switch by the largest
560 // latency of any output where either strategy is active.
561 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100562 if ((isStrategyActive(desc, STRATEGY_MEDIA,
563 SONIFICATION_HEADSET_MUSIC_DELAY,
564 sysTime) ||
565 isStrategyActive(desc, STRATEGY_SONIFICATION,
566 SONIFICATION_HEADSET_MUSIC_DELAY,
567 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700568 (delayMs < (int)desc->latency()*2)) {
569 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700571 setStrategyMute(STRATEGY_MEDIA, true, desc);
572 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700573 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700574 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
575 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700576 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
577 }
578 }
579
Eric Laurent87ffa392015-05-22 10:32:38 -0700580 if (hasPrimaryOutput()) {
581 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
582 // the device returned is not necessarily reachable via this output
583 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
584 // force routing command to audio hardware when ending call
585 // even if no device change is needed
586 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
587 rxDevice = mPrimaryOutput->device();
588 }
Eric Laurente552edb2014-03-10 17:42:56 -0700589
Eric Laurent87ffa392015-05-22 10:32:38 -0700590 if (state == AUDIO_MODE_IN_CALL) {
591 updateCallRouting(rxDevice, delayMs);
592 } else if (oldState == AUDIO_MODE_IN_CALL) {
593 if (mCallRxPatch != 0) {
594 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
595 mCallRxPatch.clear();
596 }
597 if (mCallTxPatch != 0) {
598 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
599 mCallTxPatch.clear();
600 }
601 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
602 } else {
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700606
607 // reevaluate routing on all outputs in case tracks have been started during the call
608 for (size_t i = 0; i < mOutputs.size(); i++) {
609 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
610 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
611 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800612 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700613 }
614 }
615
Eric Laurente552edb2014-03-10 17:42:56 -0700616 if (isStateInCall(state)) {
617 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700618 // force reevaluating accessibility routing when call starts
619 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621
622 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 if (state == AUDIO_MODE_RINGTONE &&
624 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700625 mLimitRingtoneVolume = true;
626 } else {
627 mLimitRingtoneVolume = false;
628 }
629}
630
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700631audio_mode_t AudioPolicyManager::getPhoneState() {
632 return mEngine->getPhoneState();
633}
634
Eric Laurente0720872014-03-11 09:30:41 -0700635void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700637{
François Gaffie2110e042015-03-24 08:41:51 +0100638 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700639 if (config == mEngine->getForceUse(usage)) {
640 return;
641 }
Eric Laurente552edb2014-03-10 17:42:56 -0700642
François Gaffie2110e042015-03-24 08:41:51 +0100643 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
644 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
645 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700646 }
François Gaffie2110e042015-03-24 08:41:51 +0100647 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
648 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
649 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700650
651 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700652 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800653
Eric Laurentdc462862016-07-19 12:29:53 -0700654 //FIXME: workaround for truncated touch sounds
655 // to be removed when the problem is handled by system UI
656 uint32_t delayMs = 0;
657 uint32_t waitMs = 0;
658 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
659 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
660 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700663 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 }
Eric Laurente552edb2014-03-10 17:42:56 -0700665 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
667 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
668 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700669 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
670 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 }
Eric Laurente552edb2014-03-10 17:42:56 -0700672 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700673 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700674 }
675 }
676
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800677 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800678 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700679 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800680 if (activeDesc->mProfile->getSupportedDevices().types() &
681 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
682 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700683 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800684 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687}
688
Eric Laurente0720872014-03-11 09:30:41 -0700689void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700690{
691 ALOGV("setSystemProperty() property %s, value %s", property, value);
692}
693
694// Find a direct output profile compatible with the parameters passed, even if the input flags do
695// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800696sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700697 audio_devices_t device,
698 uint32_t samplingRate,
699 audio_format_t format,
700 audio_channel_mask_t channelMask,
701 audio_output_flags_t flags)
702{
Eric Laurent861a6282015-05-18 15:40:16 -0700703 // only retain flags that will drive the direct output profile selection
704 // if explicitly requested
705 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700706 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
707 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700708 flags =
709 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
710
711 sp<IOProfile> profile;
712
Mikhail Naganovd4120142017-12-06 15:49:22 -0800713 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800714 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700715 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700716 samplingRate, NULL /*updatedSamplingRate*/,
717 format, NULL /*updatedFormat*/,
718 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700719 flags)) {
720 continue;
721 }
722 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100723 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700724 continue;
725 }
726 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100727 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700728 continue;
729 }
730 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700733 }
Eric Laurente552edb2014-03-10 17:42:56 -0700734 }
735 }
Eric Laurent861a6282015-05-18 15:40:16 -0700736 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700737}
738
Eric Laurentf4e63452017-11-06 19:31:46 +0000739audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700740{
Eric Laurent3b73df72014-03-11 09:06:29 -0700741 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800743
744 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
745 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
746 // format, flags, etc. This may result in some discrepancy for functions that utilize
747 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
748 // and AudioSystem::getOutputSamplingRate().
749
Eric Laurentf4e63452017-11-06 19:31:46 +0000750 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
751 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700752
Eric Laurentf4e63452017-11-06 19:31:46 +0000753 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
754 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700755}
756
Eric Laurente83b55d2014-11-14 10:06:21 -0800757status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
758 audio_io_handle_t *output,
759 audio_session_t session,
760 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700761 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800762 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200763 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700764 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800765 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700766{
Eric Laurente83b55d2014-11-14 10:06:21 -0800767 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700768 DeviceVector outputDevices;
769 routing_strategy strategy;
770 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700771 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100772 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700773
Eric Laurent8f42ea12018-08-08 09:08:25 -0700774 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
775 if (*portId != AUDIO_PORT_HANDLE_NONE) {
776 return INVALID_OPERATION;
777 }
778
Eric Laurente83b55d2014-11-14 10:06:21 -0800779 if (attr != NULL) {
780 if (!isValidAttributes(attr)) {
781 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
782 attr->usage, attr->content_type, attr->flags,
783 attr->tags);
784 return BAD_VALUE;
785 }
786 attributes = *attr;
787 } else {
788 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
789 ALOGE("getOutputForAttr(): invalid stream type");
790 return BAD_VALUE;
791 }
792 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800794
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700795 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700796 " session %d selectedDeviceId %d",
797 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
798 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700799
Eric Laurent97ac8712018-07-27 18:59:02 -0700800 *stream = streamTypefromAttributesInt(&attributes);
801
802 strategy = getStrategyForAttr(&attributes);
803
Scott Randolph7b1fd232018-06-18 15:33:03 -0700804 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700805 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
806 sp<DeviceDescriptor> deviceDesc =
807 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
808 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700809 } else {
810 // If no explict route, is there a matching dynamic policy that applies?
811 sp<SwAudioOutputDescriptor> desc;
812 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
813 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
814 if (!audio_has_proportional_frames(config->format)) {
815 return BAD_VALUE;
816 }
817 *stream = streamTypefromAttributesInt(&attributes);
818 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700819 AudioMix *mix = desc->mPolicyMix;
820 sp<DeviceDescriptor> deviceDesc =
821 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
822 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700823 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700824 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700825 }
826
827 // Virtual sources must always be dynamicaly or explicitly routed
828 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
829 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
830 return BAD_VALUE;
831 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700832 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700834
Eric Laurente83b55d2014-11-14 10:06:21 -0800835 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200836 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700837 }
838
Nadav Barb2f18162018-07-18 13:01:53 +0300839 // Set incall music only if device was explicitly set, and fallback to the device which is
840 // chosen by the engine if not.
841 // FIXME: provide a more generic approach which is not device specific and move this back
842 // to getOutputForDevice.
843 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
844 *stream == AUDIO_STREAM_MUSIC &&
845 audio_is_linear_pcm(config->format) &&
846 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700847 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300848 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
849 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700850 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300851 device = mEngine->getDeviceForStrategy(strategy);
852 }
853 }
854
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800855 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
856 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200857 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100859 *output = AUDIO_IO_HANDLE_NONE;
860 if (msdDevice != AUDIO_DEVICE_NONE) {
861 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
862 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
863 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
864 __func__, msdDevice, device);
865 device = msdDevice;
866 } else {
867 *output = AUDIO_IO_HANDLE_NONE;
868 }
869 }
870 if (*output == AUDIO_IO_HANDLE_NONE) {
871 *output = getOutputForDevice(device, session, *stream, config, flags);
872 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800873 if (*output == AUDIO_IO_HANDLE_NONE) {
874 return INVALID_OPERATION;
875 }
Paul McLeanaa981192015-03-21 09:55:15 -0700876
Eric Laurent8fc147b2018-07-22 19:13:55 -0700877 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700878 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
879 : AUDIO_PORT_HANDLE_NONE;
880
Eric Laurent8fc147b2018-07-22 19:13:55 -0700881exit:
882 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
883 .format = config->format,
884 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700885 *portId = AudioPort::getNextUniqueId();
886
Eric Laurent8fc147b2018-07-22 19:13:55 -0700887 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700888 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
889 requestedDeviceId, *stream,
890 getStrategyForAttr(&attributes),
891 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700892 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700893 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700894
895 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
896 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700897
Eric Laurente83b55d2014-11-14 10:06:21 -0800898 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700899}
900
901audio_io_handle_t AudioPolicyManager::getOutputForDevice(
902 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800903 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800905 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200906 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907{
Andy Hungc88b0642018-04-27 15:42:35 -0700908 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700909 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700910
Eric Laurente552edb2014-03-10 17:42:56 -0700911 // open a direct output if required by specified parameters
912 //force direct flag if offload flag is set: offloading implies a direct output stream
913 // and all common behaviors are driven by checking only the direct flag
914 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200915 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
916 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700917 }
Nadav Bar766fb022018-01-07 12:18:03 +0200918 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
919 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700920 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 // only allow deep buffering for music stream type
922 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200923 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700924 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700926 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
927 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800929 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700930 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200931 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700932 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800933 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200934 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700935 AUDIO_OUTPUT_FLAG_DIRECT);
936 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700937 }
Eric Laurente552edb2014-03-10 17:42:56 -0700938
Nadav Bar766fb022018-01-07 12:18:03 +0200939
Eric Laurentb732cf52014-09-24 19:08:21 -0700940 sp<IOProfile> profile;
941
942 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700943 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200944 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800945 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
946 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700947 goto non_direct_output;
948 }
949
Andy Hung2ddee192015-12-18 17:34:44 -0800950 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
951 // This prevents creating an offloaded track and tearing it down immediately after start
952 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700953 // FIXME: We should check the audio session here but we do not have it in this context.
954 // This may prevent offloading in rare situations where effects are left active by apps
955 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700956
Nadav Bar766fb022018-01-07 12:18:03 +0200957 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800958 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700959 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800960 config->sample_rate,
961 config->format,
962 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200963 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700964 }
965
Eric Laurent1c333e22014-05-20 10:48:17 -0700966 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700967 // exclusive outputs for MMAP and Offload are enforced by different session ids.
968 for (size_t i = 0; i < mOutputs.size(); i++) {
969 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
970 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
971 // reuse direct output if currently open by the same client
972 // and configured with same parameters
973 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700974 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700975 (config->channel_mask == desc->mChannelMask) &&
976 (session == desc->mDirectClientSession)) {
977 desc->mDirectOpenCount++;
978 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
979 mOutputs.keyAt(i), session);
980 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700981 }
982 }
983 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800984
985 if (!profile->canOpenNewIo()) {
986 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
Eric Laurent861a6282015-05-18 15:40:16 -0700988
Eric Laurent3974e3b2017-12-07 17:58:43 -0800989 sp<SwAudioOutputDescriptor> outputDesc =
990 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800991
Mikhail Naganov708e0382018-05-30 09:53:04 -0700992 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800993 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
994 : String8("");
995
Dean Wheatley3023b382018-08-09 07:42:40 +1000996 // MSD patch may be using the only output stream that can service this request. Release
997 // MSD patch to prioritize this request over any active output on MSD.
998 AudioPatchCollection msdPatches = getMsdPatches();
999 for (size_t i = 0; i < msdPatches.size(); i++) {
1000 const auto& patch = msdPatches[i];
1001 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1002 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1003 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1004 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1005 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1006 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1007 releaseAudioPatch(patch->mHandle, mUidCached);
1008 break;
1009 }
1010 }
1011 }
1012
Nadav Bar766fb022018-01-07 12:18:03 +02001013 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001014
1015 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001016 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001017 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001018 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001019 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1020 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1021 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1022 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1023 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001024 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001025 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001027 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001028 if (audio_is_linear_pcm(config->format) &&
1029 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 goto non_direct_output;
1031 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001032 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001034 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001035 outputDesc->mDirectClientSession = session;
1036
Eric Laurente552edb2014-03-10 17:42:56 -07001037 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001038 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001039 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001040 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001041 return output;
1042 }
1043
Eric Laurentb732cf52014-09-24 19:08:21 -07001044non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001045
1046 // A request for HW A/V sync cannot fallback to a mixed output because time
1047 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001048 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001049 return AUDIO_IO_HANDLE_NONE;
1050 }
1051
Eric Laurente552edb2014-03-10 17:42:56 -07001052 // ignoring channel mask due to downmix capability in mixer
1053
1054 // open a non direct output
1055
1056 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001057 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001058 // get which output is suitable for the specified stream. The actual
1059 // routing change will happen when startOutput() will be called
1060 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1061
Eric Laurent8838a382014-09-08 16:44:28 -07001062 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001063 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1064 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001065 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001066 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001067 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001068 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001069
Eric Laurente552edb2014-03-10 17:42:56 -07001070 return output;
1071}
1072
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001073sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1074 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1075 if (msdModule != 0) {
1076 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1077 msdModule->getHandle());
1078 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1079 }
1080 return 0;
1081}
1082
1083audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
1084 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1085 if (msdModule != 0) {
1086 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1087 }
1088 return AUDIO_DEVICE_NONE;
1089}
1090
1091const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1092 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001093 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1094 if (msdModule != 0) {
1095 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1096 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1097 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1098 const struct audio_port_config *source = &patch->mPatch.sources[j];
1099 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1100 source->ext.device.hw_module == msdModule->getHandle()) {
1101 msdPatches.addAudioPatch(patch->mHandle, patch);
1102 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001103 }
1104 }
1105 }
1106 return msdPatches;
1107}
1108
1109status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1110 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1111{
1112 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1113 if (msdModule == nullptr) {
1114 ALOGE("%s() unable to get MSD module", __func__);
1115 return NO_INIT;
1116 }
1117 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1118 if (deviceModule == nullptr) {
1119 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1120 return NO_INIT;
1121 }
1122 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1123 if (inputProfiles.isEmpty()) {
1124 ALOGE("%s() no input profiles for MSD module", __func__);
1125 return NO_INIT;
1126 }
1127 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1128 if (outputProfiles.isEmpty()) {
1129 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1130 return NO_INIT;
1131 }
1132 AudioProfileVector msdProfiles;
1133 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1134 for (const auto &inProfile : inputProfiles) {
1135 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1136 msdProfiles.appendVector(inProfile->getAudioProfiles());
1137 }
1138 }
1139 AudioProfileVector deviceProfiles;
1140 for (const auto &outProfile : outputProfiles) {
1141 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1142 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1143 }
1144 }
1145 struct audio_config_base bestSinkConfig;
1146 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1147 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1148 &bestSinkConfig);
1149 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001150 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1151 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001152 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001153 }
1154 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1155 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1156 sinkConfig->format = bestSinkConfig.format;
1157 // For encoded streams force direct flag to prevent downstream mixing.
1158 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1159 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1160 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1161 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1162 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1163 sourceConfig->format = bestSinkConfig.format;
1164 // Copy input stream directly without any processing (e.g. resampling).
1165 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1166 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1167 if (hwAvSync) {
1168 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1169 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1170 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1171 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1172 }
1173 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1174 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1175 sinkConfig->config_mask |= config_mask;
1176 sourceConfig->config_mask |= config_mask;
1177 return NO_ERROR;
1178}
1179
1180PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1181{
1182 PatchBuilder patchBuilder;
1183 patchBuilder.addSource(getMsdAudioInDevice()).
1184 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1185 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1186 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1187 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1188 // For now, we just forcefully try with HwAvSync first.
1189 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1190 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1191 getBestMsdAudioProfileFor(
1192 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1193 if (res == NO_ERROR) {
1194 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1195 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1196 }
1197 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1198 " supporting PCM format conversion.", __func__);
1199 return patchBuilder;
1200}
1201
1202status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1203 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1204 if (outputDevice == AUDIO_DEVICE_NONE) {
1205 // Use media strategy for unspecified output device. This should only
1206 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1207 // therefore invalidate explicit routing requests.
1208 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1209 }
1210 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1211 const struct audio_patch* patch = patchBuilder.patch();
1212 const AudioPatchCollection msdPatches = getMsdPatches();
1213 if (!msdPatches.isEmpty()) {
1214 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1215 "The current MSD prototype only supports one output patch");
1216 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1217 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1218 return NO_ERROR;
1219 }
1220 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1221 }
1222 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1223 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1224 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1225 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1226 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1227 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1228 return status;
1229}
1230
Eric Laurente0720872014-03-11 09:30:41 -07001231audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001232 audio_output_flags_t flags,
1233 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001234{
1235 // select one output among several that provide a path to a particular device or set of
1236 // devices (the list was previously build by getOutputsForDevice()).
1237 // The priority is as follows:
1238 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001239 // 2: the output with the bit depth the closest to the requested one
1240 // 3: the primary output
1241 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001242
1243 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001244 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001245 }
1246 if (outputs.size() == 1) {
1247 return outputs[0];
1248 }
1249
1250 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001251 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1252 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1253 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001254 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1255 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001256
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001257 for (audio_io_handle_t output : outputs) {
1258 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001259 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001260 // if a valid format is specified, skip output if not compatible
1261 if (format != AUDIO_FORMAT_INVALID) {
1262 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001263 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001264 continue;
1265 }
1266 } else if (!audio_is_linear_pcm(format)) {
1267 continue;
1268 }
Eric Laurente6930022016-02-11 10:20:40 -08001269 if (AudioPort::isBetterFormatMatch(
1270 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001271 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001272 bestFormat = outputDesc->mFormat;
1273 }
Eric Laurent8838a382014-09-08 16:44:28 -07001274 }
1275
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001276 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001277 if (commonFlags >= maxCommonFlags) {
1278 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001279 if (format != AUDIO_FORMAT_INVALID
1280 && AudioPort::isBetterFormatMatch(
1281 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001282 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001283 bestFormatForFlags = outputDesc->mFormat;
1284 }
1285 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001286 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001287 maxCommonFlags = commonFlags;
1288 bestFormatForFlags = outputDesc->mFormat;
1289 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001290 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001292 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001293 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
1295 }
1296 }
1297
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001298 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001299 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001300 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001302 return outputForFormat;
1303 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001304 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001305 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001306 }
1307
1308 return outputs[0];
1309}
1310
Eric Laurent8fc147b2018-07-22 19:13:55 -07001311status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001312{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001313 ALOGV("%s portId %d", __FUNCTION__, portId);
1314
1315 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1316 if (outputDesc == 0) {
1317 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001318 return BAD_VALUE;
1319 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001320 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001321
Eric Laurent8fc147b2018-07-22 19:13:55 -07001322 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001323 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001324
Eric Laurent733ce942017-12-07 12:18:25 -08001325 status_t status = outputDesc->start();
1326 if (status != NO_ERROR) {
1327 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001328 }
1329
Eric Laurent97ac8712018-07-27 18:59:02 -07001330 uint32_t delayMs;
1331 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001332
1333 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001334 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001335 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001336 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001337 if (delayMs != 0) {
1338 usleep(delayMs * 1000);
1339 }
1340
1341 return status;
1342}
1343
Eric Laurent97ac8712018-07-27 18:59:02 -07001344status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1345 const sp<TrackClientDescriptor>& client,
1346 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001347{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001348 // cannot start playback of STREAM_TTS if any other output is being used
1349 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001350
1351 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001352 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001353 if (stream == AUDIO_STREAM_TTS) {
1354 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001355 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 return INVALID_OPERATION;
1357 } else {
1358 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1359 }
1360 } else {
1361 // some playback other than beacon starts
1362 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1363 }
1364
Eric Laurent77305a62016-07-25 16:39:22 -07001365 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001366 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001367 bool force = !outputDesc->isActive() &&
1368 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369
Eric Laurent97ac8712018-07-27 18:59:02 -07001370 audio_devices_t device = AUDIO_DEVICE_NONE;
1371 AudioMix *policyMix = NULL;
1372 const char *address = NULL;
1373 if (outputDesc->mPolicyMix != NULL) {
1374 policyMix = outputDesc->mPolicyMix;
1375 address = policyMix->mDeviceAddress.string();
1376 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1377 device = policyMix->mDeviceType;
1378 } else {
1379 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1380 }
1381 }
1382
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001383 // requiresMuteCheck is false when we can bypass mute strategy.
1384 // It covers a common case when there is no materially active audio
1385 // and muting would result in unnecessary delay and dropped audio.
1386 const uint32_t outputLatencyMs = outputDesc->latency();
1387 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1388
Eric Laurente552edb2014-03-10 17:42:56 -07001389 // increment usage count for this stream on the requested output:
1390 // NOTE that the usage count is the same for duplicated output and hardware output which is
1391 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001392 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001393
1394 if (client->hasPreferredDevice(true)) {
1395 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1396 if (device != outputDesc->device()) {
1397 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1398 }
1399 }
Eric Laurente552edb2014-03-10 17:42:56 -07001400
Eric Laurent36829f92017-04-07 19:04:42 -07001401 if (stream == AUDIO_STREAM_MUSIC) {
1402 selectOutputForMusicEffects();
1403 }
1404
Eric Laurent592dd7b2018-08-05 18:58:48 -07001405 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001406 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001407 if (device == AUDIO_DEVICE_NONE) {
1408 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 }
Eric Laurent36829f92017-04-07 19:04:42 -07001410
Eric Laurente552edb2014-03-10 17:42:56 -07001411 routing_strategy strategy = getStrategy(stream);
1412 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001413 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1414 (beaconMuteLatency > 0);
1415 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001416 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001417 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001418 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001419 // An output has a shared device if
1420 // - managed by the same hw module
1421 // - supports the currently selected device
1422 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1423 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1424
Eric Laurent77305a62016-07-25 16:39:22 -07001425 // force a device change if any other output is:
1426 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001427 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001428 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001429 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001430 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001431 // change the device currently selected by the other output.
1432 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001433 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001434 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001435 force = true;
1436 }
1437 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001438 // a notification so that audio focus effect can propagate, or that a mute/unmute
1439 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001440 const uint32_t latencyMs = desc->latency();
1441 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1442
1443 if (shouldWait && isActive && (waitMs < latencyMs)) {
1444 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001445 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001446
1447 // Require mute check if another output is on a shared device
1448 // and currently active to have proper drain and avoid pops.
1449 // Note restoring AudioTracks onto this output needs to invoke
1450 // a volume ramp if there is no mute.
1451 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001452 }
1453 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001454
1455 const uint32_t muteWaitMs =
1456 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001457
Eric Laurente552edb2014-03-10 17:42:56 -07001458 // apply volume rules for current stream and device if necessary
1459 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001460 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001461 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001462 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001463
1464 // update the outputs if starting an output with a stream that can affect notification
1465 // routing
1466 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001467
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001468 // force reevaluating accessibility routing when ringtone or alarm starts
1469 if (strategy == STRATEGY_SONIFICATION) {
1470 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1471 }
Eric Laurentdc462862016-07-19 12:29:53 -07001472
1473 if (waitMs > muteWaitMs) {
1474 *delayMs = waitMs - muteWaitMs;
1475 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001476
1477 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1478 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1479 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1480 // change occurs after the MixerThread starts and causes a stream volume
1481 // glitch.
1482 //
1483 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001484 }
Eric Laurentdc462862016-07-19 12:29:53 -07001485
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001486 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1487 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1488 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1489 }
1490
Eric Laurent97ac8712018-07-27 18:59:02 -07001491 // Automatically enable the remote submix input when output is started on a re routing mix
1492 // of type MIX_TYPE_RECORDERS
1493 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1494 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1495 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1496 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1497 address,
1498 "remote-submix");
1499 }
1500
Eric Laurente552edb2014-03-10 17:42:56 -07001501 return NO_ERROR;
1502}
1503
Eric Laurent8fc147b2018-07-22 19:13:55 -07001504status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001505{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506 ALOGV("%s portId %d", __FUNCTION__, portId);
1507
1508 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1509 if (outputDesc == 0) {
1510 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001511 return BAD_VALUE;
1512 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001513 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001514
Eric Laurent97ac8712018-07-27 18:59:02 -07001515 ALOGV("stopOutput() output %d, stream %d, session %d",
1516 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent97ac8712018-07-27 18:59:02 -07001518 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001519
Eric Laurent733ce942017-12-07 12:18:25 -08001520 if (status == NO_ERROR ) {
1521 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001522 }
1523 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001524}
1525
Eric Laurent97ac8712018-07-27 18:59:02 -07001526status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1527 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001528{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001529 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001530 audio_stream_type_t stream = client->stream();
1531
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001532 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1533
Eric Laurent592dd7b2018-08-05 18:58:48 -07001534 if (outputDesc->streamActiveCount(stream) > 0) {
1535 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001536 // Automatically disable the remote submix input when output is stopped on a
1537 // re routing mix of type MIX_TYPE_RECORDERS
1538 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1539 outputDesc->mPolicyMix != NULL &&
1540 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1541 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1542 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1543 outputDesc->mPolicyMix->mDeviceAddress,
1544 "remote-submix");
1545 }
1546 }
1547 bool forceDeviceUpdate = false;
1548 if (client->hasPreferredDevice(true)) {
1549 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1550 forceDeviceUpdate = true;
1551 }
1552
Eric Laurente552edb2014-03-10 17:42:56 -07001553 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001554 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001555
Eric Laurente552edb2014-03-10 17:42:56 -07001556 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001557 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001558 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001559 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001560 // delay the device switch by twice the latency because stopOutput() is executed when
1561 // the track stop() command is received and at that time the audio track buffer can
1562 // still contain data that needs to be drained. The latency only covers the audio HAL
1563 // and kernel buffers. Also the latency does not always include additional delay in the
1564 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001565 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001566
1567 // force restoring the device selection on other active outputs if it differs from the
1568 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001569 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001570 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001571 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001572 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001573 desc->isActive() &&
1574 outputDesc->sharesHwModuleWith(desc) &&
1575 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001576 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1577 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001578
Eric Laurentc75307b2015-03-17 15:29:32 -07001579 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001580 newDevice2,
1581 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001582 delayMs);
1583 // re-apply device specific volume if not done by setOutputDevice()
1584 if (!force) {
1585 applyStreamVolumes(desc, newDevice2, delayMs);
1586 }
Eric Laurente552edb2014-03-10 17:42:56 -07001587 }
1588 }
1589 // update the outputs if stopping one with a stream that can affect notification routing
1590 handleNotificationRoutingForStream(stream);
1591 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001592
1593 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1594 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1595 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1596 }
1597
Eric Laurent36829f92017-04-07 19:04:42 -07001598 if (stream == AUDIO_STREAM_MUSIC) {
1599 selectOutputForMusicEffects();
1600 }
Eric Laurente552edb2014-03-10 17:42:56 -07001601 return NO_ERROR;
1602 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001603 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001604 return INVALID_OPERATION;
1605 }
1606}
1607
Eric Laurent8fc147b2018-07-22 19:13:55 -07001608void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001609{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001610 ALOGV("%s portId %d", __FUNCTION__, portId);
1611
1612 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1613 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001614 // If an output descriptor is closed due to a device routing change,
1615 // then there are race conditions with releaseOutput from tracks
1616 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1617 // destroyed shortly thereafter.
1618 //
1619 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001620 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001621 return;
1622 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001623
1624 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001625
Eric Laurent8fc147b2018-07-22 19:13:55 -07001626 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1627 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001628 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001629 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001630 return;
1631 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632 if (--outputDesc->mDirectOpenCount == 0) {
1633 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001634 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001635 }
1636 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001637 // stopOutput() needs to be successfully called before releaseOutput()
1638 // otherwise there may be inaccurate stream reference counts.
1639 // This is checked in outputDesc->removeClient below.
1640 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001641}
1642
Eric Laurentcaf7f482014-11-25 17:50:47 -08001643status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1644 audio_io_handle_t *input,
1645 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001646 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001647 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001648 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001649 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001650 input_type_t *inputType,
1651 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001652{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001653 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001654 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001655 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001656
Eric Laurentad2e7b92017-09-14 20:06:42 -07001657 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001658 // handle legacy remote submix case where the address was not always specified
1659 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001660 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001661 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001662 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001663 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001664 sp<AudioInputDescriptor> inputDesc;
1665 sp<RecordClientDescriptor> clientDesc;
1666 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001667 bool isSoundTrigger;
1668 audio_devices_t device;
1669
1670 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1671 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1672 return INVALID_OPERATION;
1673 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001674
Eric Laurentfe231122017-11-17 17:48:06 -08001675 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1676 inputSource = AUDIO_SOURCE_MIC;
1677 }
1678
Paul McLean466dc8e2015-04-17 13:15:36 -06001679 // Explicit routing?
1680 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001681 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001682 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001683 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001684
Eric Laurentad2e7b92017-09-14 20:06:42 -07001685 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1686 // possible
1687 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1688 *input != AUDIO_IO_HANDLE_NONE) {
1689 ssize_t index = mInputs.indexOfKey(*input);
1690 if (index < 0) {
1691 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1692 status = BAD_VALUE;
1693 goto error;
1694 }
1695 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001696 RecordClientVector clients = inputDesc->getClientsForSession(session);
1697 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001698 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1699 status = BAD_VALUE;
1700 goto error;
1701 }
1702 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1703 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001704 // corresponds to a new client and is only permitted from the same UID.
1705 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001706 if (clients.size() > 1) {
1707 for (const auto& client : clients) {
1708 // The client map is ordered by key values (portId) and portIds are allocated
1709 // incrementaly. So the first client in this list is the one opened by audio flinger
1710 // when the mmap stream is created and should be ignored as it does not correspond
1711 // to an actual client
1712 if (client == *clients.cbegin()) {
1713 continue;
1714 }
1715 if (uid != client->uid() && !client->isSilenced()) {
1716 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1717 uid, client->portId(), client->uid());
1718 status = INVALID_OPERATION;
1719 goto error;
1720 }
Eric Laurent331679c2018-04-16 17:03:16 -07001721 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001722 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001723 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001724 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001727 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001728 }
1729
1730 *input = AUDIO_IO_HANDLE_NONE;
1731 *inputType = API_INPUT_INVALID;
1732
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733 halInputSource = inputSource;
1734
Eric Laurentc447ded2015-01-06 08:47:05 -08001735 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001736 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1738 if (status != NO_ERROR) {
1739 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001740 }
1741 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001742 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1743 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001745 if (deviceDesc != 0) {
1746 device = deviceDesc->type();
1747 } else {
1748 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1749 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001750 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001751 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001752 status = BAD_VALUE;
1753 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001754 }
Eric Laurentc722f302014-12-10 11:21:49 -08001755 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001756 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001757 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1758 // there is an external policy, but this input is attached to a mix of recorders,
1759 // meaning it receives audio injected into the framework, so the recorder doesn't
1760 // know about it and is therefore considered "legacy"
1761 *inputType = API_INPUT_LEGACY;
1762 } else {
1763 // recording a mix of players defined by an external policy, we're rerouting for
1764 // an external policy
1765 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1766 }
Eric Laurentc722f302014-12-10 11:21:49 -08001767 } else if (audio_is_remote_submix_device(device)) {
1768 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001769 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001770 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1771 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001772 } else {
1773 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001774 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001775
Eric Laurent599c7582015-12-07 18:05:55 -08001776 }
1777
Eric Laurent8f42ea12018-08-08 09:08:25 -07001778 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001779 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001780 policyMix);
1781 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001782 status = INVALID_OPERATION;
1783 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001784 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001785
Eric Laurent8f42ea12018-08-08 09:08:25 -07001786exit:
1787
Mikhail Naganov708e0382018-05-30 09:53:04 -07001788 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001789 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001790 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001791
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1793 mSoundTriggerSessions.indexOfKey(session) > 0;
1794 *portId = AudioPort::getNextUniqueId();
1795
Eric Laurent8fc147b2018-07-22 19:13:55 -07001796 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001797 *attr, *config, requestedDeviceId,
1798 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001800 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001801
1802 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1803 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001804
Eric Laurent599c7582015-12-07 18:05:55 -08001805 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806
1807error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001809}
1810
1811
1812audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1813 String8 address,
1814 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001815 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001816 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001817 audio_input_flags_t flags,
1818 AudioMix *policyMix)
1819{
1820 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1821 audio_source_t halInputSource = inputSource;
1822 bool isSoundTrigger = false;
1823
1824 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1825 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1826 if (index >= 0) {
1827 input = mSoundTriggerSessions.valueFor(session);
1828 isSoundTrigger = true;
1829 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1830 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1831 } else {
1832 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001833 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001834 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001835 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001836 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001837 }
1838
Andy Hungf129b032015-04-07 13:45:50 -07001839 // find a compatible input profile (not necessarily identical in parameters)
1840 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001841 // sampling rate and flags may be updated by getInputProfile
1842 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1843 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001844 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001845 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001846 audio_input_flags_t profileFlags = flags;
1847 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001848 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001849 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001850 profileSamplingRate, profileFormat, profileChannelMask,
1851 profileFlags);
1852 if (profile != 0) {
1853 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001854 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1855 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001856 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1857 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1858 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001859 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001860 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1861 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001862 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001863 }
Eric Laurente552edb2014-03-10 17:42:56 -07001864 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001865 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001866 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001867 if (samplingRate == 0) {
1868 samplingRate = profileSamplingRate;
1869 }
Eric Laurente552edb2014-03-10 17:42:56 -07001870
Eric Laurent322b4d22015-04-03 15:57:54 -07001871 if (profile->getModuleHandle() == 0) {
1872 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001873 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001874 }
1875
Eric Laurent3974e3b2017-12-07 17:58:43 -08001876 if (!profile->canOpenNewIo()) {
1877 return AUDIO_IO_HANDLE_NONE;
1878 }
1879
Eric Laurentfe231122017-11-17 17:48:06 -08001880 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001881
Eric Laurentfe231122017-11-17 17:48:06 -08001882 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1883 lConfig.sample_rate = profileSamplingRate;
1884 lConfig.channel_mask = profileChannelMask;
1885 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001886
Eric Laurent53b810e2017-12-10 17:25:10 -08001887 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001888 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001889 // the inputs vector must be of size >= 1, but we don't want to crash here
1890 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1891 }
1892
Eric Laurentfe231122017-11-17 17:48:06 -08001893 status_t status = inputDesc->open(&lConfig, device, address,
1894 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001895
1896 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001897 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001898 (profileSamplingRate != lConfig.sample_rate) ||
1899 !audio_formats_match(profileFormat, lConfig.format) ||
1900 (profileChannelMask != lConfig.channel_mask)) {
1901 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001902 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001903 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001904 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001905 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001906 }
Eric Laurent599c7582015-12-07 18:05:55 -08001907 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001908 }
1909
Eric Laurentc722f302014-12-10 11:21:49 -08001910 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001911
Eric Laurent599c7582015-12-07 18:05:55 -08001912 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001913 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001914
Eric Laurent599c7582015-12-07 18:05:55 -08001915 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001916}
1917
Eric Laurentbb948092017-01-23 18:33:30 -08001918//static
1919bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1920{
1921 return (source == AUDIO_SOURCE_HOTWORD) ||
1922 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1923 (source == AUDIO_SOURCE_FM_TUNER);
1924}
1925
Chris Thornton2b864642017-06-27 21:26:07 -07001926// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1927bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1928 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1929 bool soundTriggerSupportsConcurrentCapture = false;
1930 unsigned int numModules = 0;
1931 struct sound_trigger_module_descriptor* nModules = NULL;
1932
1933 status_t status = SoundTrigger::listModules(nModules, &numModules);
1934 if (status == NO_ERROR && numModules != 0) {
1935 nModules = (struct sound_trigger_module_descriptor*) calloc(
1936 numModules, sizeof(struct sound_trigger_module_descriptor));
1937 if (nModules == NULL) {
1938 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1939 // ram the next time this function is called.
1940 ALOGE("Failed to allocate buffer for module descriptors");
1941 return false;
1942 }
1943
1944 status = SoundTrigger::listModules(nModules, &numModules);
1945 if (status == NO_ERROR) {
1946 soundTriggerSupportsConcurrentCapture = true;
1947 for (size_t i = 0; i < numModules; ++i) {
1948 soundTriggerSupportsConcurrentCapture &=
1949 nModules[i].properties.concurrent_capture;
1950 }
1951 }
1952 free(nModules);
1953 }
1954 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1955 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1956 }
1957 return mSoundTriggerSupportsConcurrentCapture;
1958}
1959
Eric Laurentfb66dd92016-01-28 18:32:03 -08001960
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001962 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001963 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001964{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001965 *concurrency = API_INPUT_CONCURRENCY_NONE;
1966
1967 ALOGV("%s portId %d", __FUNCTION__, portId);
1968
1969 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1970 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001971 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001972 return BAD_VALUE;
1973 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001974 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001975 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001976 if (client->active()) {
1977 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1978 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001979 }
1980
Eric Laurent8f42ea12018-08-08 09:08:25 -07001981 audio_session_t session = client->session();
1982
1983 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1984 __FUNCTION__, input, session, silenced, *concurrency);
1985
Eric Laurent74708e72017-04-07 17:13:42 -07001986 if (!is_virtual_input_device(inputDesc->mDevice)) {
1987 if (mCallTxPatch != 0 &&
1988 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1989 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001990 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001991 return INVALID_OPERATION;
1992 }
1993
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001994 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001995
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001996 // If a UID is idle and records silence and another not silenced recording starts
1997 // from another UID (idle or active) we stop the current idle UID recording in
1998 // favor of the new one - "There can be only one" TM
1999 if (!silenced) {
2000 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002001 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002002 activeDesc->getId() == inputDesc->getId()) {
2003 continue;
2004 }
2005
Eric Laurent8f42ea12018-08-08 09:08:25 -07002006 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2007 for (const auto& activeClient : activeClients) {
2008 if (activeClient->isSilenced()) {
2009 closeClient(activeClient->portId());
2010 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2011 portId, activeClient->portId());
2012 activeInputs = mInputs.getActiveInputs();
2013 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002014 }
2015 }
2016 }
2017
2018 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002019 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002020 activeDesc->getId() == inputDesc->getId()) {
2021 continue;
2022 }
2023
Eric Laurent74708e72017-04-07 17:13:42 -07002024 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002025 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002026 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2027 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002028 ALOGW("%s input %d failed for HOTWORD: "
2029 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002030 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002031 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002032 return INVALID_OPERATION;
2033 }
2034 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2036 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002037 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002038 return INVALID_OPERATION;
2039 }
2040 } else {
2041 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002042 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002043 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002044 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002045 return INVALID_OPERATION;
2046 }
2047 }
2048 }
2049
Chris Thornton2b864642017-06-27 21:26:07 -07002050 // We only need to check if the sound trigger session supports concurrent capture if the
2051 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2052 // that's running.
2053 const bool allowConcurrentWithSoundTrigger =
2054 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2055
Eric Laurent74708e72017-04-07 17:13:42 -07002056 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002057 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002058 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2059 continue;
2060 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002061 RecordClientVector activeHotwordClients =
2062 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2063 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002064 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065
2066 for (const auto& activeClient : activeHotwordClients) {
2067 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2068 sessions.add(activeClient->session());
2069 closeClient(activeClient->portId());
2070 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2071 input, activeDesc->mIoHandle);
2072 }
2073
Eric Laurent74708e72017-04-07 17:13:42 -07002074 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002075 }
2076 }
2077 }
Eric Laurente552edb2014-03-10 17:42:56 -07002078
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002079 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002080 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002081
Eric Laurent313d1e72016-01-29 09:56:57 -08002082 // increment activity count before calling getNewInputDevice() below as only active sessions
2083 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002084 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002085
Eric Laurent8f42ea12018-08-08 09:08:25 -07002086 // indicate active capture to sound trigger service if starting capture from a mic on
2087 // primary HW module
2088 audio_devices_t device = getNewInputDevice(inputDesc);
2089 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091 status_t status = inputDesc->start();
2092 if (status != NO_ERROR) {
2093 inputDesc->setClientActive(client, false);
2094 return status;
2095 }
2096
2097 if (inputDesc->activeCount() == 1) {
2098 // if input maps to a dynamic policy with an activity listener, notify of state change
2099 if ((inputDesc->mPolicyMix != NULL)
2100 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2101 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2102 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002103 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002104
Eric Laurent8f42ea12018-08-08 09:08:25 -07002105 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2106 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2107 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2108 SoundTrigger::setCaptureState(true);
2109 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002110
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111 // automatically enable the remote submix output when input is started if not
2112 // used by a policy mix of type MIX_TYPE_RECORDERS
2113 // For remote submix (a virtual device), we open only one input per capture request.
2114 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2115 String8 address = String8("");
2116 if (inputDesc->mPolicyMix == NULL) {
2117 address = String8("0");
2118 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2119 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002120 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002121 if (address != "") {
2122 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2123 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2124 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002125 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002126 }
Eric Laurente552edb2014-03-10 17:42:56 -07002127 }
2128
Eric Laurent8f42ea12018-08-08 09:08:25 -07002129 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Eric Laurente552edb2014-03-10 17:42:56 -07002131 return NO_ERROR;
2132}
2133
Eric Laurent8fc147b2018-07-22 19:13:55 -07002134status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002135{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136 ALOGV("%s portId %d", __FUNCTION__, portId);
2137
2138 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2139 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002141 return BAD_VALUE;
2142 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002144 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002145 if (!client->active()) {
2146 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002147 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 }
2149
Eric Laurent8f42ea12018-08-08 09:08:25 -07002150 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002151
Eric Laurent8f42ea12018-08-08 09:08:25 -07002152 inputDesc->stop();
2153 if (inputDesc->isActive()) {
2154 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2155 } else {
2156 // if input maps to a dynamic policy with an activity listener, notify of state change
2157 if ((inputDesc->mPolicyMix != NULL)
2158 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2159 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2160 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002161 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002162
2163 // automatically disable the remote submix output when input is stopped if not
2164 // used by a policy mix of type MIX_TYPE_RECORDERS
2165 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2166 String8 address = String8("");
2167 if (inputDesc->mPolicyMix == NULL) {
2168 address = String8("0");
2169 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2170 address = inputDesc->mPolicyMix->mDeviceAddress;
2171 }
2172 if (address != "") {
2173 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2174 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2175 address, "remote-submix");
2176 }
2177 }
2178
2179 audio_devices_t device = inputDesc->mDevice;
2180 resetInputDevice(input);
2181
2182 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2183 // primary HW module
2184 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2185 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2186 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2187 SoundTrigger::setCaptureState(false);
2188 }
2189 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002190 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002191 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002192}
2193
Eric Laurent8fc147b2018-07-22 19:13:55 -07002194void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002195{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002196 ALOGV("%s portId %d", __FUNCTION__, portId);
2197
2198 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2199 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002201 return;
2202 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002203 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002204 audio_io_handle_t input = inputDesc->mIoHandle;
2205
Eric Laurent8f42ea12018-08-08 09:08:25 -07002206 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002207
Andy Hung39efb7a2018-09-26 15:39:28 -07002208 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002209
Andy Hung39efb7a2018-09-26 15:39:28 -07002210 if (inputDesc->getClientCount() > 0) {
2211 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002212 return;
2213 }
2214
Eric Laurent05b90f82014-08-27 15:32:29 -07002215 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002216 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002217 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002218}
2219
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002221{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002222 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002223
2224 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226 }
2227}
2228
Eric Laurent8f42ea12018-08-08 09:08:25 -07002229void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2230{
2231 stopInput(portId);
2232 releaseInput(portId);
2233}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002234
Eric Laurentd4692962014-05-05 18:13:44 -07002235void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002236 bool patchRemoved = false;
2237
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002238 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002239 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002240 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002241 if (patch_index >= 0) {
2242 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002243 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002244 mAudioPatches.removeItemsAt(patch_index);
2245 patchRemoved = true;
2246 }
Eric Laurentfe231122017-11-17 17:48:06 -08002247 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002248 }
2249 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002250 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002251 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002252
2253 if (patchRemoved) {
2254 mpClientInterface->onAudioPatchListUpdate();
2255 }
Eric Laurentd4692962014-05-05 18:13:44 -07002256}
2257
Eric Laurente0720872014-03-11 09:30:41 -07002258void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002259 int indexMin,
2260 int indexMax)
2261{
2262 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002263 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002264
2265 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002266 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2267 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002268 continue;
2269 }
2270 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002271 }
Eric Laurente552edb2014-03-10 17:42:56 -07002272}
2273
Eric Laurente0720872014-03-11 09:30:41 -07002274status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002275 int index,
2276 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002277{
2278
Nadav Bar7c605f62017-12-25 00:01:52 +02002279 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2280 // app that has MODIFY_PHONE_STATE permission.
2281 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2282 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002283 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002284 return BAD_VALUE;
2285 }
2286 if (!audio_is_output_device(device)) {
2287 return BAD_VALUE;
2288 }
2289
2290 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002291 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002292
Eric Laurent1fd372e2016-04-06 14:23:53 -07002293 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002294 stream, device, index);
2295
Eric Laurent28d09f02016-03-08 10:43:05 -08002296 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002297 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2298 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 continue;
2300 }
2301 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2302 }
Eric Laurente552edb2014-03-10 17:42:56 -07002303
Eric Laurent1fd372e2016-04-06 14:23:53 -07002304 // update volume on all outputs and streams matching the following:
2305 // - The requested stream (or a stream matching for volume control) is active on the output
2306 // - The device (or devices) selected by the strategy corresponding to this stream includes
2307 // the requested device
2308 // - For non default requested device, currently selected device on the output is either the
2309 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002310 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2311 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002312 status_t status = NO_ERROR;
2313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2315 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002316 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002317 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002318 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002319 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002320 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002321 continue;
2322 }
Eric Laurent794fde22016-03-11 09:50:45 -08002323 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002324 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2325 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002326 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2327 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002328 continue;
2329 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002330 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002331 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002332 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002333 applyVolume = (curDevice & curStreamDevice) != 0;
2334 } else {
2335 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002336 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002337 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002338 // rescale index before applying to curStream as ranges may be different for
2339 // stream and curStream
2340 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002341 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002342 //FIXME: workaround for truncated touch sounds
2343 // delayed volume change for system stream to be removed when the problem is
2344 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002345 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002346 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002347 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002348 if (volStatus != NO_ERROR) {
2349 status = volStatus;
2350 }
2351 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002352 }
Eric Laurente552edb2014-03-10 17:42:56 -07002353 }
2354 return status;
2355}
2356
Eric Laurente0720872014-03-11 09:30:41 -07002357status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002358 int *index,
2359 audio_devices_t device)
2360{
2361 if (index == NULL) {
2362 return BAD_VALUE;
2363 }
2364 if (!audio_is_output_device(device)) {
2365 return BAD_VALUE;
2366 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002367 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002368 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002369 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002370 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2371 }
François Gaffiedfd74092015-03-19 12:10:59 +01002372 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002373
François Gaffied1ab2bd2015-12-02 18:20:06 +01002374 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002375 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2376 return NO_ERROR;
2377}
2378
Eric Laurent36829f92017-04-07 19:04:42 -07002379audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002380{
2381 // select one output among several suitable for global effects.
2382 // The priority is as follows:
2383 // 1: An offloaded output. If the effect ends up not being offloadable,
2384 // AudioFlinger will invalidate the track and the offloaded output
2385 // will be closed causing the effect to be moved to a PCM output.
2386 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002387 // 3: The primary output
2388 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002389
Eric Laurent3b73df72014-03-11 09:06:29 -07002390 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002391 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002392 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Eric Laurent36829f92017-04-07 19:04:42 -07002394 if (outputs.size() == 0) {
2395 return AUDIO_IO_HANDLE_NONE;
2396 }
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent36829f92017-04-07 19:04:42 -07002398 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2399 bool activeOnly = true;
2400
2401 while (output == AUDIO_IO_HANDLE_NONE) {
2402 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2403 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2404 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2405
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002406 for (audio_io_handle_t output : outputs) {
2407 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002408 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2409 continue;
2410 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002411 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2412 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002414 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002415 }
2416 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002417 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002418 }
2419 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002420 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002421 }
2422 }
2423 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2424 output = outputOffloaded;
2425 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2426 output = outputDeepBuffer;
2427 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2428 output = outputPrimary;
2429 } else {
2430 output = outputs[0];
2431 }
2432 activeOnly = false;
2433 }
2434
2435 if (output != mMusicEffectOutput) {
2436 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2437 mMusicEffectOutput = output;
2438 }
2439
2440 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002441 return output;
2442}
2443
Eric Laurent36829f92017-04-07 19:04:42 -07002444audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2445{
2446 return selectOutputForMusicEffects();
2447}
2448
Eric Laurente0720872014-03-11 09:30:41 -07002449status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002450 audio_io_handle_t io,
2451 uint32_t strategy,
2452 int session,
2453 int id)
2454{
2455 ssize_t index = mOutputs.indexOfKey(io);
2456 if (index < 0) {
2457 index = mInputs.indexOfKey(io);
2458 if (index < 0) {
2459 ALOGW("registerEffect() unknown io %d", io);
2460 return INVALID_OPERATION;
2461 }
2462 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002463 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002464}
2465
Eric Laurentc75307b2015-03-17 15:29:32 -07002466bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2467{
Eric Laurent28d09f02016-03-08 10:43:05 -08002468 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002469 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2470 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002471 continue;
2472 }
2473 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2474 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002475 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002476}
2477
2478bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2479{
2480 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2481}
2482
Eric Laurente0720872014-03-11 09:30:41 -07002483bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002484{
2485 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002486 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002487 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002488 return true;
2489 }
2490 }
2491 return false;
2492}
2493
Eric Laurent275e8e92014-11-30 15:14:47 -08002494// Register a list of custom mixes with their attributes and format.
2495// When a mix is registered, corresponding input and output profiles are
2496// added to the remote submix hw module. The profile contains only the
2497// parameters (sampling rate, format...) specified by the mix.
2498// The corresponding input remote submix device is also connected.
2499//
2500// When a remote submix device is connected, the address is checked to select the
2501// appropriate profile and the corresponding input or output stream is opened.
2502//
2503// When capture starts, getInputForAttr() will:
2504// - 1 look for a mix matching the address passed in attribtutes tags if any
2505// - 2 if none found, getDeviceForInputSource() will:
2506// - 2.1 look for a mix matching the attributes source
2507// - 2.2 if none found, default to device selection by policy rules
2508// At this time, the corresponding output remote submix device is also connected
2509// and active playback use cases can be transferred to this mix if needed when reconnecting
2510// after AudioTracks are invalidated
2511//
2512// When playback starts, getOutputForAttr() will:
2513// - 1 look for a mix matching the address passed in attribtutes tags if any
2514// - 2 if none found, look for a mix matching the attributes usage
2515// - 3 if none found, default to device and output selection by policy rules.
2516
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002517status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002518{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2520 status_t res = NO_ERROR;
2521
2522 sp<HwModule> rSubmixModule;
2523 // examine each mix's route type
2524 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002527 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002529 break;
2530 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002531 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002532 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002534 rSubmixModule = mHwModules.getModuleFromName(
2535 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2536 if (rSubmixModule == 0) {
2537 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2538 i);
2539 res = INVALID_OPERATION;
2540 break;
2541 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002542 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002543
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 String8 address = mix.mDeviceAddress;
2545 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2546 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2547 } else {
2548 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2549 }
François Gaffie036e1e92015-03-19 10:16:24 +01002550
Eric Laurent97ac8712018-07-27 18:59:02 -07002551 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002552 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 res = INVALID_OPERATION;
2554 break;
2555 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 audio_config_t outputConfig = mix.mFormat;
2557 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2559 // stereo and let audio flinger do the channel conversion if needed.
2560 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2561 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2562 rSubmixModule->addOutputProfile(address, &outputConfig,
2563 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2564 rSubmixModule->addInputProfile(address, &inputConfig,
2565 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002566
Eric Laurent97ac8712018-07-27 18:59:02 -07002567 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2569 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2570 address.string(), "remote-submix");
2571 } else {
2572 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2573 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2574 address.string(), "remote-submix");
2575 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002576 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2577 String8 address = mix.mDeviceAddress;
2578 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002579 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2580 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002581
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002582 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2584 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2585 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2586 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2587 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2588 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002589 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2590 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002592 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002593 } else {
2594 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 }
2596 break;
2597 }
2598 }
2599
2600 if (res != NO_ERROR) {
2601 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002602 i, device, address.string());
2603 res = INVALID_OPERATION;
2604 break;
2605 } else if (!foundOutput) {
2606 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2607 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002608 res = INVALID_OPERATION;
2609 break;
2610 }
Eric Laurentc722f302014-12-10 11:21:49 -08002611 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002612 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002613 if (res != NO_ERROR) {
2614 unregisterPolicyMixes(mixes);
2615 }
2616 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002617}
2618
2619status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2620{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002621 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002622 status_t res = NO_ERROR;
2623 sp<HwModule> rSubmixModule;
2624 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002625 for (const auto& mix : mixes) {
2626 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002627
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002628 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002629 rSubmixModule = mHwModules.getModuleFromName(
2630 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2631 if (rSubmixModule == 0) {
2632 res = INVALID_OPERATION;
2633 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 }
2635 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002636
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002637 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002638
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002639 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2640 res = INVALID_OPERATION;
2641 continue;
2642 }
2643
2644 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2645 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2646 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2647 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2648 address.string(), "remote-submix");
2649 }
2650 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2651 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2652 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2653 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2654 address.string(), "remote-submix");
2655 }
2656 rSubmixModule->removeOutputProfile(address);
2657 rSubmixModule->removeInputProfile(address);
2658
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002659 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2660 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002661 res = INVALID_OPERATION;
2662 continue;
2663 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002664 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002665 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002666 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002667}
2668
Eric Laurente552edb2014-03-10 17:42:56 -07002669
Eric Laurente0720872014-03-11 09:30:41 -07002670status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002671{
Eric Laurente552edb2014-03-10 17:42:56 -07002672 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002673 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2674 result.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);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002678 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2679 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)) {
2684 result.appendFormat(" Force use for %s: %d\n",
2685 forceUses[i], mEngine->getForceUse(i));
2686 }
2687 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2688 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2689 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002690 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002691
François Gaffie112b0af2015-11-19 16:13:25 +01002692 mAvailableOutputDevices.dump(fd, String8("Available output"));
2693 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002694 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002695 mOutputs.dump(fd);
2696 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002697 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002698 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002699 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002700 mPolicyMixes.dump(fd);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07002701 mAudioSources.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002702
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002703 if (!mSurroundFormats.empty()) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07002704 result = String8("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002705 size_t i = 0;
2706 for (const auto& fmt : mSurroundFormats) {
2707 result.append(i++ == 0 ? " " : ", ");
2708 std::string sfmt;
2709 FormatConverter::toString(fmt, sfmt);
2710 result.appendFormat("%s", sfmt.c_str());
2711 }
2712 result.append("\n");
2713 write(fd, result.string(), result.size());
2714 }
2715
Eric Laurente552edb2014-03-10 17:42:56 -07002716 return NO_ERROR;
2717}
2718
2719// This function checks for the parameters which can be offloaded.
2720// This can be enhanced depending on the capability of the DSP and policy
2721// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002722bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002723{
2724 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002725 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002726 offloadInfo.sample_rate, offloadInfo.channel_mask,
2727 offloadInfo.format,
2728 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2729 offloadInfo.has_video);
2730
Andy Hung2ddee192015-12-18 17:34:44 -08002731 if (mMasterMono) {
2732 return false; // no offloading if mono is set.
2733 }
2734
Eric Laurente552edb2014-03-10 17:42:56 -07002735 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002736 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2737 ALOGV("offload disabled by audio.offload.disable");
2738 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002739 }
2740
2741 // Check if stream type is music, then only allow offload as of now.
2742 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2743 {
2744 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2745 return false;
2746 }
2747
2748 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002749 const bool allowOffloadWithVideo =
2750 property_get_bool("audio.offload.video", false /* default_value */);
2751 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002752 ALOGV("isOffloadSupported: has_video == true, returning false");
2753 return false;
2754 }
2755
2756 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002757 const int min_duration_secs = property_get_int32(
2758 "audio.offload.min.duration.secs", -1 /* default_value */);
2759 if (min_duration_secs >= 0) {
2760 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2761 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2762 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002763 return false;
2764 }
2765 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2766 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2767 return false;
2768 }
2769
2770 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2771 // creating an offloaded track and tearing it down immediately after start when audioflinger
2772 // detects there is an active non offloadable effect.
2773 // FIXME: We should check the audio session here but we do not have it in this context.
2774 // This may prevent offloading in rare situations where effects are left active by apps
2775 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002776 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002777 return false;
2778 }
2779
2780 // See if there is a profile to support this.
2781 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002782 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002783 offloadInfo.sample_rate,
2784 offloadInfo.format,
2785 offloadInfo.channel_mask,
2786 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002787 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2788 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002789}
2790
Eric Laurent6a94d692014-05-20 11:18:06 -07002791status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2792 audio_port_type_t type,
2793 unsigned int *num_ports,
2794 struct audio_port *ports,
2795 unsigned int *generation)
2796{
2797 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2798 generation == NULL) {
2799 return BAD_VALUE;
2800 }
2801 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2802 if (ports == NULL) {
2803 *num_ports = 0;
2804 }
2805
2806 size_t portsWritten = 0;
2807 size_t portsMax = *num_ports;
2808 *num_ports = 0;
2809 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002810 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2811 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002813 for (const auto& dev : mAvailableOutputDevices) {
2814 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002815 continue;
2816 }
2817 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002818 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002819 }
2820 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002821 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 }
2823 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002824 for (const auto& dev : mAvailableInputDevices) {
2825 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002826 continue;
2827 }
2828 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002829 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002830 }
2831 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 }
2834 }
2835 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2836 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2837 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2838 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2839 }
2840 *num_ports += mInputs.size();
2841 }
2842 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002843 size_t numOutputs = 0;
2844 for (size_t i = 0; i < mOutputs.size(); i++) {
2845 if (!mOutputs[i]->isDuplicated()) {
2846 numOutputs++;
2847 if (portsWritten < portsMax) {
2848 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2849 }
2850 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 }
Eric Laurent84c70242014-06-23 08:46:27 -07002852 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
2854 }
2855 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002856 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002857 return NO_ERROR;
2858}
2859
Eric Laurent99fcae42018-05-17 16:59:18 -07002860status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002861{
Eric Laurent99fcae42018-05-17 16:59:18 -07002862 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2863 return BAD_VALUE;
2864 }
2865 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2866 if (dev != 0) {
2867 dev->toAudioPort(port);
2868 return NO_ERROR;
2869 }
2870 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2871 if (dev != 0) {
2872 dev->toAudioPort(port);
2873 return NO_ERROR;
2874 }
2875 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2876 if (out != 0) {
2877 out->toAudioPort(port);
2878 return NO_ERROR;
2879 }
2880 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2881 if (in != 0) {
2882 in->toAudioPort(port);
2883 return NO_ERROR;
2884 }
2885 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002886}
2887
Eric Laurent6a94d692014-05-20 11:18:06 -07002888status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2889 audio_patch_handle_t *handle,
2890 uid_t uid)
2891{
2892 ALOGV("createAudioPatch()");
2893
2894 if (handle == NULL || patch == NULL) {
2895 return BAD_VALUE;
2896 }
2897 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2898
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002899 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002900 return BAD_VALUE;
2901 }
2902 // only one source per audio patch supported for now
2903 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 return INVALID_OPERATION;
2905 }
Eric Laurent874c42872014-08-08 15:13:39 -07002906
2907 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 return INVALID_OPERATION;
2909 }
Eric Laurent874c42872014-08-08 15:13:39 -07002910 for (size_t i = 0; i < patch->num_sinks; i++) {
2911 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2912 return INVALID_OPERATION;
2913 }
2914 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002915
2916 sp<AudioPatch> patchDesc;
2917 ssize_t index = mAudioPatches.indexOfKey(*handle);
2918
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2920 patch->sources[0].role,
2921 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002922#if LOG_NDEBUG == 0
2923 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002924 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002925 patch->sinks[i].role,
2926 patch->sinks[i].type);
2927 }
2928#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002929
2930 if (index >= 0) {
2931 patchDesc = mAudioPatches.valueAt(index);
2932 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2933 mUidCached, patchDesc->mUid, uid);
2934 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2935 return INVALID_OPERATION;
2936 }
2937 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002938 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002939 }
2940
2941 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002942 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002943 if (outputDesc == NULL) {
2944 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2945 return BAD_VALUE;
2946 }
Eric Laurent84c70242014-06-23 08:46:27 -07002947 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2948 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 if (patchDesc != 0) {
2950 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2951 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2952 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2953 return BAD_VALUE;
2954 }
2955 }
Eric Laurent874c42872014-08-08 15:13:39 -07002956 DeviceVector devices;
2957 for (size_t i = 0; i < patch->num_sinks; i++) {
2958 // Only support mix to devices connection
2959 // TODO add support for mix to mix connection
2960 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2961 ALOGV("createAudioPatch() source mix but sink is not a device");
2962 return INVALID_OPERATION;
2963 }
2964 sp<DeviceDescriptor> devDesc =
2965 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2966 if (devDesc == 0) {
2967 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2968 return BAD_VALUE;
2969 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002970
François Gaffie53615e22015-03-19 09:24:12 +01002971 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002972 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002973 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002974 NULL, // updatedSamplingRate
2975 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002976 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002977 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002978 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002979 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002980 ALOGV("createAudioPatch() profile not supported for device %08x",
2981 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002982 return INVALID_OPERATION;
2983 }
2984 devices.add(devDesc);
2985 }
2986 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 return INVALID_OPERATION;
2988 }
Eric Laurent874c42872014-08-08 15:13:39 -07002989
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 // TODO: reconfigure output format and channels here
2991 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002992 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002993 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002994 index = mAudioPatches.indexOfKey(*handle);
2995 if (index >= 0) {
2996 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2997 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2998 }
2999 patchDesc = mAudioPatches.valueAt(index);
3000 patchDesc->mUid = uid;
3001 ALOGV("createAudioPatch() success");
3002 } else {
3003 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3004 return INVALID_OPERATION;
3005 }
3006 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3007 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3008 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003009 // only one sink supported when connecting an input device to a mix
3010 if (patch->num_sinks > 1) {
3011 return INVALID_OPERATION;
3012 }
François Gaffie53615e22015-03-19 09:24:12 +01003013 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 if (inputDesc == NULL) {
3015 return BAD_VALUE;
3016 }
3017 if (patchDesc != 0) {
3018 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3019 return BAD_VALUE;
3020 }
3021 }
3022 sp<DeviceDescriptor> devDesc =
3023 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3024 if (devDesc == 0) {
3025 return BAD_VALUE;
3026 }
3027
François Gaffie53615e22015-03-19 09:24:12 +01003028 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003029 devDesc->mAddress,
3030 patch->sinks[0].sample_rate,
3031 NULL, /*updatedSampleRate*/
3032 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003033 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003034 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003035 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003036 // FIXME for the parameter type,
3037 // and the NONE
3038 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003039 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 return INVALID_OPERATION;
3041 }
3042 // TODO: reconfigure output format and channels here
3043 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003044 devDesc->type(), inputDesc->mIoHandle);
3045 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 index = mAudioPatches.indexOfKey(*handle);
3047 if (index >= 0) {
3048 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3049 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3050 }
3051 patchDesc = mAudioPatches.valueAt(index);
3052 patchDesc->mUid = uid;
3053 ALOGV("createAudioPatch() success");
3054 } else {
3055 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3056 return INVALID_OPERATION;
3057 }
3058 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3059 // device to device connection
3060 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003061 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003062 return BAD_VALUE;
3063 }
3064 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 sp<DeviceDescriptor> srcDeviceDesc =
3066 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003067 if (srcDeviceDesc == 0) {
3068 return BAD_VALUE;
3069 }
Eric Laurent874c42872014-08-08 15:13:39 -07003070
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 //update source and sink with our own data as the data passed in the patch may
3072 // be incomplete.
3073 struct audio_patch newPatch = *patch;
3074 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003075
Eric Laurent874c42872014-08-08 15:13:39 -07003076 for (size_t i = 0; i < patch->num_sinks; i++) {
3077 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3078 ALOGV("createAudioPatch() source device but one sink is not a device");
3079 return INVALID_OPERATION;
3080 }
3081
3082 sp<DeviceDescriptor> sinkDeviceDesc =
3083 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3084 if (sinkDeviceDesc == 0) {
3085 return BAD_VALUE;
3086 }
3087 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3088
Eric Laurent3bcf8592015-04-03 12:13:24 -07003089 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003090 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003091 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003092 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003093 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003094 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003095 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003096 return INVALID_OPERATION;
3097 }
Eric Laurent874c42872014-08-08 15:13:39 -07003098 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003099 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003100 // if the sink device is reachable via an opened output stream, request to go via
3101 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003102 audio_io_handle_t output = selectOutput(outputs,
3103 AUDIO_OUTPUT_FLAG_NONE,
3104 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003105 if (output != AUDIO_IO_HANDLE_NONE) {
3106 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3107 if (outputDesc->isDuplicated()) {
3108 return INVALID_OPERATION;
3109 }
3110 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003111 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003112 newPatch.num_sources = 2;
3113 }
Eric Laurent83b88082014-06-20 18:31:16 -07003114 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003115 }
3116 // TODO: check from routing capabilities in config file and other conflicting patches
3117
Mikhail Naganovdc769682018-05-04 15:34:08 -07003118 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3119 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003120 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3121 status);
3122 return INVALID_OPERATION;
3123 }
3124 } else {
3125 return BAD_VALUE;
3126 }
3127 } else {
3128 return BAD_VALUE;
3129 }
3130 return NO_ERROR;
3131}
3132
3133status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3134 uid_t uid)
3135{
3136 ALOGV("releaseAudioPatch() patch %d", handle);
3137
3138 ssize_t index = mAudioPatches.indexOfKey(handle);
3139
3140 if (index < 0) {
3141 return BAD_VALUE;
3142 }
3143 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3144 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3145 mUidCached, patchDesc->mUid, uid);
3146 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3147 return INVALID_OPERATION;
3148 }
3149
3150 struct audio_patch *patch = &patchDesc->mPatch;
3151 patchDesc->mUid = mUidCached;
3152 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003154 if (outputDesc == NULL) {
3155 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3156 return BAD_VALUE;
3157 }
3158
Eric Laurentc75307b2015-03-17 15:29:32 -07003159 setOutputDevice(outputDesc,
3160 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 true,
3162 0,
3163 NULL);
3164 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3165 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003166 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 if (inputDesc == NULL) {
3168 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3169 return BAD_VALUE;
3170 }
3171 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003172 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003173 true,
3174 NULL);
3175 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3177 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3178 status, patchDesc->mAfPatchHandle);
3179 removeAudioPatch(patchDesc->mHandle);
3180 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003181 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003182 } else {
3183 return BAD_VALUE;
3184 }
3185 } else {
3186 return BAD_VALUE;
3187 }
3188 return NO_ERROR;
3189}
3190
3191status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3192 struct audio_patch *patches,
3193 unsigned int *generation)
3194{
François Gaffie53615e22015-03-19 09:24:12 +01003195 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 return BAD_VALUE;
3197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003199 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003200}
3201
Eric Laurente1715a42014-05-20 11:30:42 -07003202status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003203{
Eric Laurente1715a42014-05-20 11:30:42 -07003204 ALOGV("setAudioPortConfig()");
3205
3206 if (config == NULL) {
3207 return BAD_VALUE;
3208 }
3209 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3210 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003211 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3212 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003213 }
3214
Eric Laurenta121f902014-06-03 13:32:54 -07003215 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003216 if (config->type == AUDIO_PORT_TYPE_MIX) {
3217 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003218 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003219 if (outputDesc == NULL) {
3220 return BAD_VALUE;
3221 }
Eric Laurent84c70242014-06-23 08:46:27 -07003222 ALOG_ASSERT(!outputDesc->isDuplicated(),
3223 "setAudioPortConfig() called on duplicated output %d",
3224 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003225 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003226 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003227 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003228 if (inputDesc == NULL) {
3229 return BAD_VALUE;
3230 }
Eric Laurenta121f902014-06-03 13:32:54 -07003231 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003232 } else {
3233 return BAD_VALUE;
3234 }
3235 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3236 sp<DeviceDescriptor> deviceDesc;
3237 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3238 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3239 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3240 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3241 } else {
3242 return BAD_VALUE;
3243 }
3244 if (deviceDesc == NULL) {
3245 return BAD_VALUE;
3246 }
Eric Laurenta121f902014-06-03 13:32:54 -07003247 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003248 } else {
3249 return BAD_VALUE;
3250 }
3251
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003252 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003253 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3254 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003255 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003256 audioPortConfig->toAudioPortConfig(&newConfig, config);
3257 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003258 }
Eric Laurenta121f902014-06-03 13:32:54 -07003259 if (status != NO_ERROR) {
3260 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003261 }
Eric Laurente1715a42014-05-20 11:30:42 -07003262
3263 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003264}
3265
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003266void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3267{
Eric Laurentd60560a2015-04-10 11:31:20 -07003268 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003269 clearAudioPatches(uid);
3270 clearSessionRoutes(uid);
3271}
3272
Eric Laurent6a94d692014-05-20 11:18:06 -07003273void AudioPolicyManager::clearAudioPatches(uid_t uid)
3274{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003275 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003276 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3277 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003278 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003279 }
3280 }
3281}
3282
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003283void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3284 audio_io_handle_t ouptutToSkip)
3285{
3286 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3287 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3288 for (size_t j = 0; j < mOutputs.size(); j++) {
3289 if (mOutputs.keyAt(j) == ouptutToSkip) {
3290 continue;
3291 }
3292 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3293 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3294 continue;
3295 }
3296 // If the default device for this strategy is on another output mix,
3297 // invalidate all tracks in this strategy to force re connection.
3298 // Otherwise select new device on the output mix.
3299 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003300 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003301 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3302 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3303 }
3304 }
3305 } else {
3306 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3307 setOutputDevice(outputDesc, newDevice, false);
3308 }
3309 }
3310}
3311
3312void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3313{
3314 // remove output routes associated with this uid
3315 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003316 for (size_t i = 0; i < mOutputs.size(); i++) {
3317 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003318 for (const auto& client : outputDesc->getClientIterable()) {
3319 if (client->hasPreferredDevice() && client->uid() == uid) {
3320 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3321 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003322 }
3323 }
3324 }
3325 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003326 for (const auto& strategy : affectedStrategies) {
3327 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003328 }
3329
3330 // remove input routes associated with this uid
3331 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003332 for (size_t i = 0; i < mInputs.size(); i++) {
3333 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003334 for (const auto& client : inputDesc->getClientIterable()) {
3335 if (client->hasPreferredDevice() && client->uid() == uid) {
3336 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3337 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003338 }
3339 }
3340 }
3341 // reroute inputs if necessary
3342 SortedVector<audio_io_handle_t> inputsToClose;
3343 for (size_t i = 0; i < mInputs.size(); i++) {
3344 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003345 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003346 inputsToClose.add(inputDesc->mIoHandle);
3347 }
3348 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003349 for (const auto& input : inputsToClose) {
3350 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003351 }
3352}
3353
Eric Laurentd60560a2015-04-10 11:31:20 -07003354void AudioPolicyManager::clearAudioSources(uid_t uid)
3355{
3356 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003357 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3358 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003359 stopAudioSource(mAudioSources.keyAt(i));
3360 }
3361 }
3362}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003363
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003364status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3365 audio_io_handle_t *ioHandle,
3366 audio_devices_t *device)
3367{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003368 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3369 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003370 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003371
François Gaffiedf372692015-03-19 10:43:27 +01003372 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003373}
3374
Eric Laurentd60560a2015-04-10 11:31:20 -07003375status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003376 const audio_attributes_t *attributes,
3377 audio_port_handle_t *portId,
3378 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003379{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003380 ALOGV("%s", __FUNCTION__);
3381 *portId = AUDIO_PORT_HANDLE_NONE;
3382
3383 if (source == NULL || attributes == NULL || portId == NULL) {
3384 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3385 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003386 return BAD_VALUE;
3387 }
3388
Eric Laurentd60560a2015-04-10 11:31:20 -07003389 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3390 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003391 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3392 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003393 return INVALID_OPERATION;
3394 }
3395
3396 sp<DeviceDescriptor> srcDeviceDesc =
3397 mAvailableInputDevices.getDevice(source->ext.device.type,
3398 String8(source->ext.device.address));
3399 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003400 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 return BAD_VALUE;
3402 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003403
3404 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003405
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003406 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003407 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003408
3409 sp<SourceClientDescriptor> sourceDesc =
3410 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003411 streamTypefromAttributesInt(attributes),
3412 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003413
3414 status_t status = connectAudioSource(sourceDesc);
3415 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003416 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003417 }
3418 return status;
3419}
3420
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003421status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003422{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003424
3425 // make sure we only have one patch per source.
3426 disconnectAudioSource(sourceDesc);
3427
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003428 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003429 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003430 audio_stream_type_t stream = sourceDesc->stream();
3431 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003432
3433 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3434 sp<DeviceDescriptor> sinkDeviceDesc =
3435 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3436
3437 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003438
3439 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3440 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003441 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003442 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3443 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3444 // create patch between src device and output device
3445 // create Hwoutput and add to mHwOutputs
3446 } else {
3447 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3448 audio_io_handle_t output =
3449 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3450 if (output == AUDIO_IO_HANDLE_NONE) {
3451 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3452 return INVALID_OPERATION;
3453 }
3454 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3455 if (outputDesc->isDuplicated()) {
3456 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3457 return INVALID_OPERATION;
3458 }
Eric Laurent733ce942017-12-07 12:18:25 -08003459 status_t status = outputDesc->start();
3460 if (status != NO_ERROR) {
3461 return status;
3462 }
3463
Eric Laurentd60560a2015-04-10 11:31:20 -07003464 // create a special patch with no sink and two sources:
3465 // - the second source indicates to PatchPanel through which output mix this patch should
3466 // be connected as well as the stream type for volume control
3467 // - the sink is defined by whatever output device is currently selected for the output
3468 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003469 PatchBuilder patchBuilder;
3470 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3471 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003472 &afPatchHandle,
3473 0);
3474 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3475 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003476 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003477 if (status != NO_ERROR) {
3478 ALOGW("%s patch panel could not connect device patch, error %d",
3479 __FUNCTION__, status);
3480 return INVALID_OPERATION;
3481 }
3482 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003483 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003484
3485 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003486 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003487 return status;
3488 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003489 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003490 if (delayMs != 0) {
3491 usleep(delayMs * 1000);
3492 }
3493 }
3494
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003495 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3496 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003497
3498 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003499}
3500
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003501status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003502{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003503 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3504 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003505 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003506 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 return BAD_VALUE;
3508 }
3509 status_t status = disconnectAudioSource(sourceDesc);
3510
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003511 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003512 return status;
3513}
3514
Andy Hung2ddee192015-12-18 17:34:44 -08003515status_t AudioPolicyManager::setMasterMono(bool mono)
3516{
3517 if (mMasterMono == mono) {
3518 return NO_ERROR;
3519 }
3520 mMasterMono = mono;
3521 // if enabling mono we close all offloaded devices, which will invalidate the
3522 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3523 // for recreating the new AudioTrack as non-offloaded PCM.
3524 //
3525 // If disabling mono, we leave all tracks as is: we don't know which clients
3526 // and tracks are able to be recreated as offloaded. The next "song" should
3527 // play back offloaded.
3528 if (mMasterMono) {
3529 Vector<audio_io_handle_t> offloaded;
3530 for (size_t i = 0; i < mOutputs.size(); ++i) {
3531 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3532 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3533 offloaded.push(desc->mIoHandle);
3534 }
3535 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003536 for (const auto& handle : offloaded) {
3537 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003538 }
3539 }
3540 // update master mono for all remaining outputs
3541 for (size_t i = 0; i < mOutputs.size(); ++i) {
3542 updateMono(mOutputs.keyAt(i));
3543 }
3544 return NO_ERROR;
3545}
3546
3547status_t AudioPolicyManager::getMasterMono(bool *mono)
3548{
3549 *mono = mMasterMono;
3550 return NO_ERROR;
3551}
3552
Eric Laurentac9cef52017-06-09 15:46:26 -07003553float AudioPolicyManager::getStreamVolumeDB(
3554 audio_stream_type_t stream, int index, audio_devices_t device)
3555{
3556 return computeVolume(stream, index, device);
3557}
3558
jiabin81772902018-04-02 17:52:27 -07003559status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3560 audio_format_t *surroundFormats,
3561 bool *surroundFormatsEnabled,
3562 bool reported)
3563{
3564 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3565 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3566 return BAD_VALUE;
3567 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003568 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3569 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003570
3571 // Only return value if there is HDMI output.
3572 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3573 return INVALID_OPERATION;
3574 }
3575
3576 size_t formatsWritten = 0;
3577 size_t formatsMax = *numSurroundFormats;
3578 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003579 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003580 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003581 // Return formats from HDMI profiles, that have already been resolved by
3582 // checkOutputsForDevice().
3583 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3584 AUDIO_DEVICE_OUT_HDMI);
3585 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3586 FormatVector supportedFormats =
3587 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3588 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003589 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003590 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003591 } else {
3592 for (const auto& pair : mConfig.getSurroundFormats()) {
3593 if (pair.second.count(supportedFormats[j]) != 0) {
3594 formats.insert(pair.first);
3595 break;
3596 }
3597 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003598 }
3599 }
jiabin81772902018-04-02 17:52:27 -07003600 }
3601 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003602 for (const auto& pair : mConfig.getSurroundFormats()) {
3603 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003604 }
3605 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003606 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003607 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003608 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003609 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003610 if (mConfig.getSurroundFormats().count(format) == 0) {
3611 // Check sub-formats
3612 for (const auto& pair : mConfig.getSurroundFormats()) {
3613 for (const auto& subformat : pair.second) {
3614 formatEnabled = mSurroundFormats.count(subformat) != 0;
3615 if (formatEnabled) break;
3616 }
3617 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003618 }
3619 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003620 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003621 }
3622 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3623 }
3624 (*numSurroundFormats)++;
3625 }
3626 return NO_ERROR;
3627}
3628
3629status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3630{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003631 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003632 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003633 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3634 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003635 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003636 return BAD_VALUE;
3637 }
3638
3639 // Should only be called when MANUAL.
3640 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3641 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3642 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003643 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003644 return INVALID_OPERATION;
3645 }
3646
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003647 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003648 return NO_ERROR;
3649 }
3650
3651 // The operation is valid only when there is HDMI output available.
3652 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003653 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003654 return INVALID_OPERATION;
3655 }
3656
Mikhail Naganov2563f232018-09-27 14:48:01 -07003657 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003658 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003659 mSurroundFormats.insert(audioFormat);
3660 for (const auto& subFormat : formatIter->second) {
3661 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003662 }
3663 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003664 mSurroundFormats.erase(audioFormat);
3665 for (const auto& subFormat : formatIter->second) {
3666 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003667 }
3668 }
3669
3670 sp<SwAudioOutputDescriptor> outputDesc;
3671 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003672 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003673 AUDIO_DEVICE_OUT_HDMI);
3674 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3675 // Simulate reconnection to update enabled surround sound formats.
3676 String8 address = hdmiOutputDevices[i]->mAddress;
3677 String8 name = hdmiOutputDevices[i]->getName();
3678 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3679 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3680 address.c_str(),
3681 name.c_str());
3682 if (status != NO_ERROR) {
3683 continue;
3684 }
3685 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3686 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3687 address.c_str(),
3688 name.c_str());
3689 profileUpdated |= (status == NO_ERROR);
3690 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003691 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003692 AUDIO_DEVICE_IN_HDMI);
3693 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3694 // Simulate reconnection to update enabled surround sound formats.
3695 String8 address = hdmiInputDevices[i]->mAddress;
3696 String8 name = hdmiInputDevices[i]->getName();
3697 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3698 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3699 address.c_str(),
3700 name.c_str());
3701 if (status != NO_ERROR) {
3702 continue;
3703 }
3704 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3705 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3706 address.c_str(),
3707 name.c_str());
3708 profileUpdated |= (status == NO_ERROR);
3709 }
3710
jiabin81772902018-04-02 17:52:27 -07003711 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003712 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003713 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003714 }
3715
3716 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3717}
3718
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003719void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3720{
3721 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3722
3723 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3724 for (size_t i = 0; i < activeInputs.size(); i++) {
3725 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003726 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3727 for (const auto& client : clients) {
3728 if (uid == client->uid()) {
3729 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003730 }
3731 }
3732 }
3733}
3734
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003735status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003736{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003737 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003738
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003739 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003740 if (patchDesc == 0) {
3741 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003742 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003743 return BAD_VALUE;
3744 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003745 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003746
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003747 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003748 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003749 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003750 if (status == NO_ERROR) {
3751 swOutputDesc->stop();
3752 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003753 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3754 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003755 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003756 if (hwOutputDesc != 0) {
3757 // release patch between src device and output device
3758 // close Hwoutput and remove from mHwOutputs
3759 } else {
3760 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3761 }
3762 }
3763 return NO_ERROR;
3764}
3765
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003766sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003767 audio_io_handle_t output, routing_strategy strategy)
3768{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003769 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003770 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003771 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3772 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003773 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003774 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003775 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3776 source = sourceDesc;
3777 break;
3778 }
3779 }
3780 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003781}
3782
Eric Laurente552edb2014-03-10 17:42:56 -07003783// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003784// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003785// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003786uint32_t AudioPolicyManager::nextAudioPortGeneration()
3787{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003788 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003789}
3790
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003791#ifdef USE_XML_AUDIO_POLICY_CONF
3792// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3793static const char *kConfigLocationList[] =
3794 {"/odm/etc", "/vendor/etc", "/system/etc"};
3795static const int kConfigLocationListSize =
3796 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3797
3798static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3799 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003800 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003801 status_t ret;
3802
Petri Gyntherf497f292018-04-17 18:46:10 -07003803 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3804 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3805 // A2DP offload supported but disabled: try to use special XML file
3806 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3807 }
3808 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3809
3810 for (const char* fileName : fileNames) {
3811 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003812 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3813 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003814 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003815 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003816 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003817 return ret;
3818 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003819 }
3820 }
3821 return ret;
3822}
3823#endif
3824
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003825AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3826 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003827 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003828 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003829 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003830 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003831 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003832#ifdef USE_XML_AUDIO_POLICY_CONF
3833 mVolumeCurves(new VolumeCurvesCollection()),
3834 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003835 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003836#else
3837 mVolumeCurves(new StreamDescriptorCollection()),
3838 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3839 mDefaultOutputDevice),
3840#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003841 mAudioPortGeneration(1),
3842 mBeaconMuteRefCount(0),
3843 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003844 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003845 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003846 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003847 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3848 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003849{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003850}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003851
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003852AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3853 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3854{
3855 loadConfig();
3856 initialize();
3857}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003858
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003859void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003860#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003862#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3864 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003865#endif
3866 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003867 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003868 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003869}
3870
3871status_t AudioPolicyManager::initialize() {
3872 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003873
3874 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003875 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3876 if (!engineInstance) {
3877 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003878 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003879 }
3880 // Retrieve the Policy Manager Interface
3881 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3882 if (mEngine == NULL) {
3883 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003884 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003885 }
3886 mEngine->setObserver(this);
3887 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888 if (status != NO_ERROR) {
3889 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3890 return status;
3891 }
François Gaffie2110e042015-03-24 08:41:51 +01003892
Eric Laurent3a4311c2014-03-17 12:00:47 -07003893 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003894 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003895 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3896 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003897 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003898 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003899 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3900 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003901 continue;
3902 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003904 // open all output streams needed to access attached devices
3905 // except for direct output streams that are only opened when they are actually
3906 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003908 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003909 if (!outProfile->canOpenNewIo()) {
3910 ALOGE("Invalid Output profile max open count %u for profile %s",
3911 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3912 continue;
3913 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003914 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003915 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003916 continue;
3917 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003918 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003919 mTtsOutputAvailable = true;
3920 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003922 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003923 continue;
3924 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003925 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003926 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3927 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003928 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003929 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003930 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003931 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003933 if ((profileType & outputDeviceTypes) == 0) {
3934 continue;
3935 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003936 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3937 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003938 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003939 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3940 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003941 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3942 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003944 status_t status = outputDesc->open(nullptr, profileType, address,
3945 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003946
3947 if (status != NO_ERROR) {
3948 ALOGW("Cannot open output stream for device %08x on hw module %s",
3949 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003950 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003951 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003952 for (const auto& dev : supportedDevices) {
3953 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003954 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003955 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003956 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 }
3958 }
3959 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003960 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003961 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003962 }
3963 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003965 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003966 true,
3967 0,
3968 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003969 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003970 }
Eric Laurente552edb2014-03-10 17:42:56 -07003971 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003972 // open input streams needed to access attached devices to validate
3973 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003974 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003975 if (!inProfile->canOpenNewIo()) {
3976 ALOGE("Invalid Input profile max open count %u for profile %s",
3977 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3978 continue;
3979 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003980 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003981 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003982 continue;
3983 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003985 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3987
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 if ((profileType & inputDeviceTypes) == 0) {
3989 continue;
3990 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003991 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003992 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003993
Mikhail Naganov708e0382018-05-30 09:53:04 -07003994 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003995 // the inputs vector must be of size >= 1, but we don't want to crash here
3996 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3997 : String8("");
3998 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3999 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4000
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004002 status_t status = inputDesc->open(nullptr,
4003 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004004 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004005 AUDIO_SOURCE_MIC,
4006 AUDIO_INPUT_FLAG_NONE,
4007 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004008
4009 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004010 for (const auto& dev : inProfile->getSupportedDevices()) {
4011 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004012 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004013 if (index >= 0) {
4014 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4015 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004016 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004017 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004018 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 }
4020 }
Eric Laurentfe231122017-11-17 17:48:06 -08004021 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004022 } else {
4023 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004024 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004025 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004026 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004027 }
4028 }
4029 // make sure all attached devices have been allocated a unique ID
4030 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004031 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004032 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004033 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4034 continue;
4035 }
François Gaffie2110e042015-03-24 08:41:51 +01004036 // The device is now validated and can be appended to the available devices of the engine
4037 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4038 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004039 i++;
4040 }
4041 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004042 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004043 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004044 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4045 continue;
4046 }
François Gaffie2110e042015-03-24 08:41:51 +01004047 // The device is now validated and can be appended to the available devices of the engine
4048 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4049 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004050 i++;
4051 }
4052 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004053 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004054 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004055 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 }
jiabin9ff780e2018-03-19 18:19:52 -07004057 // If microphones address is empty, set it according to device type
4058 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4059 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4060 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4061 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4062 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4063 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4064 }
4065 }
4066 }
Eric Laurente552edb2014-03-10 17:42:56 -07004067
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004068 if (mPrimaryOutput == 0) {
4069 ALOGE("Failed to open primary output");
4070 status = NO_INIT;
4071 }
Eric Laurente552edb2014-03-10 17:42:56 -07004072
4073 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004074 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004075}
4076
Eric Laurente0720872014-03-11 09:30:41 -07004077AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004078{
Eric Laurente552edb2014-03-10 17:42:56 -07004079 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004080 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004081 }
4082 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004083 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 mAvailableOutputDevices.clear();
4086 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004087 mOutputs.clear();
4088 mInputs.clear();
4089 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004090 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004091 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004092}
4093
Eric Laurente0720872014-03-11 09:30:41 -07004094status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004095{
Eric Laurent87ffa392015-05-22 10:32:38 -07004096 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004097}
4098
Eric Laurente552edb2014-03-10 17:42:56 -07004099// ---
4100
Eric Laurent98e38192018-02-15 18:31:53 -08004101void AudioPolicyManager::addOutput(audio_io_handle_t output,
4102 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004103{
Eric Laurent1c333e22014-05-20 10:48:17 -07004104 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004105 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004106 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004107 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004108 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004109}
4110
François Gaffie53615e22015-03-19 09:24:12 +01004111void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4112{
4113 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004114 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004115}
4116
Eric Laurent98e38192018-02-15 18:31:53 -08004117void AudioPolicyManager::addInput(audio_io_handle_t input,
4118 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004119{
Eric Laurent1c333e22014-05-20 10:48:17 -07004120 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004121 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004122}
Eric Laurente552edb2014-03-10 17:42:56 -07004123
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004124void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004125 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004126 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004127 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004128 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004129 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004130 if (devDesc != 0) {
4131 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4132 desc->mIoHandle, address.string());
4133 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004134 }
4135}
4136
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004137status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004138 audio_policy_dev_state_t state,
4139 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004140 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004141{
François Gaffie53615e22015-03-19 09:24:12 +01004142 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004143 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004144
4145 if (audio_device_is_digital(device)) {
4146 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004147 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004148 }
Eric Laurente552edb2014-03-10 17:42:56 -07004149
Eric Laurent3b73df72014-03-11 09:06:29 -07004150 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004151 // first list already open outputs that can be routed to this device
4152 for (size_t i = 0; i < mOutputs.size(); i++) {
4153 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004154 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004155 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004156 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4157 outputs.add(mOutputs.keyAt(i));
4158 } else {
4159 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004160 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004161 }
Eric Laurente552edb2014-03-10 17:42:56 -07004162 }
4163 }
4164 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004165 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004166 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004167 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4168 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004169 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004170 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004171 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004172 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004173 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4174 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004175 }
Eric Laurente552edb2014-03-10 17:42:56 -07004176 }
4177 }
4178 }
4179
Eric Laurent7b279bb2015-12-14 10:18:23 -08004180 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004181
Eric Laurente552edb2014-03-10 17:42:56 -07004182 if (profiles.isEmpty() && outputs.isEmpty()) {
4183 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4184 return BAD_VALUE;
4185 }
4186
4187 // open outputs for matching profiles if needed. Direct outputs are also opened to
4188 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4189 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004190 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004191
4192 // nothing to do if one output is already opened for this profile
4193 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004194 for (j = 0; j < outputs.size(); j++) {
4195 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004196 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004197 // matching profile: save the sample rates, format and channel masks supported
4198 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004199 if (audio_device_is_digital(device)) {
4200 devDesc->importAudioPort(profile);
4201 }
Eric Laurente552edb2014-03-10 17:42:56 -07004202 break;
4203 }
4204 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004205 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004206 continue;
4207 }
4208
Eric Laurent3974e3b2017-12-07 17:58:43 -08004209 if (!profile->canOpenNewIo()) {
4210 ALOGW("Max Output number %u already opened for this profile %s",
4211 profile->maxOpenCount, profile->getTagName().c_str());
4212 continue;
4213 }
4214
Eric Laurent83efe1c2017-07-09 16:51:08 -07004215 ALOGV("opening output for device %08x with params %s profile %p name %s",
4216 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004217 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004218 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004219 status_t status = desc->open(nullptr, device, address,
4220 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004221
Eric Laurentfe231122017-11-17 17:48:06 -08004222 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004223 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004224 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004225 char *param = audio_device_address_to_parameter(device, address);
4226 mpClientInterface->setParameters(output, String8(param));
4227 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004228 }
Phil Burk00eeb322016-03-31 12:41:00 -07004229 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004230 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004231 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004232 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004233 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004234 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004235 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004236 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004237 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4238 profile->pickAudioProfile(
4239 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004240 config.offload_info.sample_rate = config.sample_rate;
4241 config.offload_info.channel_mask = config.channel_mask;
4242 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004243
4244 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4245 AUDIO_OUTPUT_FLAG_NONE, &output);
4246 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004247 output = AUDIO_IO_HANDLE_NONE;
4248 }
Eric Laurentd4692962014-05-05 18:13:44 -07004249 }
4250
Eric Laurentcf2c0212014-07-25 16:20:43 -07004251 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004252 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004253 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004254 sp<AudioPolicyMix> policyMix;
4255 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004256 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4257 address.string());
4258 }
François Gaffie036e1e92015-03-19 10:16:24 +01004259 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004260 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004261
Eric Laurent87ffa392015-05-22 10:32:38 -07004262 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4263 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004264 // no duplicated output for direct outputs and
4265 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004266 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004267
Eric Laurentd4692962014-05-05 18:13:44 -07004268 //TODO: configure audio effect output stage here
4269
4270 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004271 sp<SwAudioOutputDescriptor> dupOutputDesc =
4272 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4273 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4274 &duplicatedOutput);
4275 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004276 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004277 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004278 } else {
4279 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004280 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004281 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004282 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004283 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004284 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004285 }
Eric Laurente552edb2014-03-10 17:42:56 -07004286 }
4287 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004288 } else {
4289 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004290 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004291 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004292 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004293 profiles.removeAt(profile_index);
4294 profile_index--;
4295 } else {
4296 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004297 // Load digital format info only for digital devices
4298 if (audio_device_is_digital(device)) {
4299 devDesc->importAudioPort(profile);
4300 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004301
François Gaffie53615e22015-03-19 09:24:12 +01004302 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004303 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4304 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004305 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 NULL/*patch handle*/, address.string());
4307 }
Eric Laurente552edb2014-03-10 17:42:56 -07004308 ALOGV("checkOutputsForDevice(): adding output %d", output);
4309 }
4310 }
4311
4312 if (profiles.isEmpty()) {
4313 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4314 return BAD_VALUE;
4315 }
Eric Laurentd4692962014-05-05 18:13:44 -07004316 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004317 // check if one opened output is not needed any more after disconnecting one device
4318 for (size_t i = 0; i < mOutputs.size(); i++) {
4319 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004320 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004321 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004322 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004323 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004324 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004325 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004326 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4327 mOutputs.keyAt(i));
4328 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004329 }
Eric Laurente552edb2014-03-10 17:42:56 -07004330 }
4331 }
Eric Laurentd4692962014-05-05 18:13:44 -07004332 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004333 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004334 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4335 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004336 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004337 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004338 "clearing direct output profile %zu on module %s",
4339 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004340 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004341 }
4342 }
4343 }
4344 }
4345 return NO_ERROR;
4346}
4347
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004348status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004349 audio_policy_dev_state_t state,
4350 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004351 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004352{
Paul McLean9080a4c2015-06-18 08:24:02 -07004353 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004354 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004355
4356 if (audio_device_is_digital(device)) {
4357 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004358 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004359 }
4360
Eric Laurentd4692962014-05-05 18:13:44 -07004361 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4362 // first list already open inputs that can be routed to this device
4363 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4364 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004365 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004366 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4367 inputs.add(mInputs.keyAt(input_index));
4368 }
4369 }
4370
4371 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004372 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004373 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004374 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004375 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004376 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004377 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004378
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004379 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004380 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004381 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004382 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004383 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4384 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004385 }
Eric Laurentd4692962014-05-05 18:13:44 -07004386 }
4387 }
4388 }
4389
4390 if (profiles.isEmpty() && inputs.isEmpty()) {
4391 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4392 return BAD_VALUE;
4393 }
4394
4395 // open inputs for matching profiles if needed. Direct inputs are also opened to
4396 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4397 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4398
Eric Laurent1c333e22014-05-20 10:48:17 -07004399 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004400
Eric Laurentd4692962014-05-05 18:13:44 -07004401 // nothing to do if one input is already opened for this profile
4402 size_t input_index;
4403 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4404 desc = mInputs.valueAt(input_index);
4405 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004406 if (audio_device_is_digital(device)) {
4407 devDesc->importAudioPort(profile);
4408 }
Eric Laurentd4692962014-05-05 18:13:44 -07004409 break;
4410 }
4411 }
4412 if (input_index != mInputs.size()) {
4413 continue;
4414 }
4415
Eric Laurent3974e3b2017-12-07 17:58:43 -08004416 if (!profile->canOpenNewIo()) {
4417 ALOGW("Max Input number %u already opened for this profile %s",
4418 profile->maxOpenCount, profile->getTagName().c_str());
4419 continue;
4420 }
4421
Eric Laurentfe231122017-11-17 17:48:06 -08004422 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004423 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004424 status_t status = desc->open(nullptr,
4425 device,
4426 address,
4427 AUDIO_SOURCE_MIC,
4428 AUDIO_INPUT_FLAG_NONE,
4429 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004430
Eric Laurentcf2c0212014-07-25 16:20:43 -07004431 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004432 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004433 char *param = audio_device_address_to_parameter(device, address);
4434 mpClientInterface->setParameters(input, String8(param));
4435 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004436 }
Phil Burk00eeb322016-03-31 12:41:00 -07004437 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004438 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004439 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004440 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004441 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004442 }
4443
4444 if (input != 0) {
4445 addInput(input, desc);
4446 }
4447 } // endif input != 0
4448
Eric Laurentcf2c0212014-07-25 16:20:43 -07004449 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004450 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004451 profiles.removeAt(profile_index);
4452 profile_index--;
4453 } else {
4454 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004455 if (audio_device_is_digital(device)) {
4456 devDesc->importAudioPort(profile);
4457 }
Eric Laurentd4692962014-05-05 18:13:44 -07004458 ALOGV("checkInputsForDevice(): adding input %d", input);
4459 }
4460 } // end scan profiles
4461
4462 if (profiles.isEmpty()) {
4463 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4464 return BAD_VALUE;
4465 }
4466 } else {
4467 // Disconnect
4468 // check if one opened input is not needed any more after disconnecting one device
4469 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4470 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004471 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004472 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4473 mInputs.keyAt(input_index));
4474 inputs.add(mInputs.keyAt(input_index));
4475 }
4476 }
4477 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004478 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004479 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004480 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004481 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004482 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004483 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004484 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4485 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004486 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004487 }
4488 }
4489 }
4490 } // end disconnect
4491
4492 return NO_ERROR;
4493}
4494
4495
Eric Laurente0720872014-03-11 09:30:41 -07004496void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004497{
4498 ALOGV("closeOutput(%d)", output);
4499
Eric Laurentc75307b2015-03-17 15:29:32 -07004500 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004501 if (outputDesc == NULL) {
4502 ALOGW("closeOutput() unknown output %d", output);
4503 return;
4504 }
François Gaffie036e1e92015-03-19 10:16:24 +01004505 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004506
Eric Laurente552edb2014-03-10 17:42:56 -07004507 // look for duplicated outputs connected to the output being removed.
4508 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004509 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 if (dupOutputDesc->isDuplicated() &&
4511 (dupOutputDesc->mOutput1 == outputDesc ||
4512 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004513 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004514 if (dupOutputDesc->mOutput1 == outputDesc) {
4515 outputDesc2 = dupOutputDesc->mOutput2;
4516 } else {
4517 outputDesc2 = dupOutputDesc->mOutput1;
4518 }
4519 // As all active tracks on duplicated output will be deleted,
4520 // and as they were also referenced on the other output, the reference
4521 // count for their stream type must be adjusted accordingly on
4522 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004523 const bool wasActive = outputDesc2->isActive();
4524 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4525 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004526 }
Eric Laurent733ce942017-12-07 12:18:25 -08004527 // stop() will be a no op if the output is still active but is needed in case all
4528 // active streams refcounts where cleared above
4529 if (wasActive) {
4530 outputDesc2->stop();
4531 }
Eric Laurente552edb2014-03-10 17:42:56 -07004532 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4533 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4534
4535 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004536 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004537 }
4538 }
4539
Eric Laurent05b90f82014-08-27 15:32:29 -07004540 nextAudioPortGeneration();
4541
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004542 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004543 if (index >= 0) {
4544 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004545 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004546 mAudioPatches.removeItemsAt(index);
4547 mpClientInterface->onAudioPatchListUpdate();
4548 }
4549
Eric Laurentfe231122017-11-17 17:48:06 -08004550 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004551
François Gaffie53615e22015-03-19 09:24:12 +01004552 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004553 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004554
4555 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4556 // no direct outputs are open.
4557 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4558 bool directOutputOpen = false;
4559 for (size_t i = 0; i < mOutputs.size(); i++) {
4560 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4561 directOutputOpen = true;
4562 break;
4563 }
4564 }
4565 if (!directOutputOpen) {
4566 ALOGV("no direct outputs open, reset MSD patch");
4567 setMsdPatch();
4568 }
4569 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004570}
4571
4572void AudioPolicyManager::closeInput(audio_io_handle_t input)
4573{
4574 ALOGV("closeInput(%d)", input);
4575
4576 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4577 if (inputDesc == NULL) {
4578 ALOGW("closeInput() unknown input %d", input);
4579 return;
4580 }
4581
Eric Laurent6a94d692014-05-20 11:18:06 -07004582 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004583
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004584 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004585 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004586 if (index >= 0) {
4587 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004588 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004589 mAudioPatches.removeItemsAt(index);
4590 mpClientInterface->onAudioPatchListUpdate();
4591 }
4592
Eric Laurentfe231122017-11-17 17:48:06 -08004593 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004594 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004595
4596 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4597 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4598 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4599 SoundTrigger::setCaptureState(false);
4600 }
Eric Laurente552edb2014-03-10 17:42:56 -07004601}
4602
Eric Laurentc75307b2015-03-17 15:29:32 -07004603SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4604 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004605 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004606{
4607 SortedVector<audio_io_handle_t> outputs;
4608
4609 ALOGVV("getOutputsForDevice() device %04x", device);
4610 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004611 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004612 i, openOutputs.valueAt(i)->isDuplicated(),
4613 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004614 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4615 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4616 outputs.add(openOutputs.keyAt(i));
4617 }
4618 }
4619 return outputs;
4620}
4621
Mikhail Naganov37977152018-07-11 15:54:44 -07004622void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4623{
4624 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4625 // output is suspended before any tracks are moved to it
4626 checkA2dpSuspend();
4627 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004628 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004629 updateDevicesAndOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004630 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
4631 setMsdPatch();
4632 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004633}
4634
Eric Laurente0720872014-03-11 09:30:41 -07004635void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
4637 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4638 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4639 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4640 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4641
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004642 // also take into account external policy-related changes: add all outputs which are
4643 // associated with policies in the "before" and "after" output vectors
4644 ALOGVV("checkOutputForStrategy(): policy related outputs");
4645 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004646 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004647 if (desc != 0 && desc->mPolicyMix != NULL) {
4648 srcOutputs.add(desc->mIoHandle);
4649 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4650 }
4651 }
4652 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004653 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004654 if (desc != 0 && desc->mPolicyMix != NULL) {
4655 dstOutputs.add(desc->mIoHandle);
4656 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4657 }
4658 }
4659
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004660 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004661 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4662 // audio from invalidated tracks will be rendered when unmuting
4663 uint32_t maxLatency = 0;
4664 for (audio_io_handle_t srcOut : srcOutputs) {
4665 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4666 if (desc != 0 && maxLatency < desc->latency()) {
4667 maxLatency = desc->latency();
4668 }
4669 }
Eric Laurente552edb2014-03-10 17:42:56 -07004670 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4671 strategy, srcOutputs[0], dstOutputs[0]);
4672 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004673 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004674 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4675 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004677 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004678 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004679 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004680 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004681 if (source != 0){
4682 connectAudioSource(source);
4683 }
Eric Laurente552edb2014-03-10 17:42:56 -07004684 }
4685
4686 // Move effects associated to this strategy from previous output to new output
4687 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004688 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004689 }
4690 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004691 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004692 if (getStrategy((audio_stream_type_t)i) == strategy) {
4693 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695 }
4696 }
4697}
4698
Eric Laurente0720872014-03-11 09:30:41 -07004699void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
François Gaffie2110e042015-03-24 08:41:51 +01004701 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004702 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004703 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004704 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004705 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004706 checkOutputForStrategy(STRATEGY_SONIFICATION);
4707 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004708 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004709 checkOutputForStrategy(STRATEGY_MEDIA);
4710 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004711 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004712}
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004715{
François Gaffie53615e22015-03-19 09:24:12 +01004716 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004717 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004718 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004719 return;
4720 }
4721
Eric Laurent3a4311c2014-03-17 12:00:47 -07004722 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004723 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4724 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4725 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004726
4727 // if suspended, restore A2DP output if:
4728 // ((SCO device is NOT connected) ||
4729 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4730 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004731 //
Eric Laurentf732e072016-08-03 19:30:28 -07004732 // if not suspended, suspend A2DP output if:
4733 // (SCO device is connected) &&
4734 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4735 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004736 //
4737 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004738 if (!isScoConnected ||
4739 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4740 AUDIO_POLICY_FORCE_BT_SCO) &&
4741 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4742 AUDIO_POLICY_FORCE_BT_SCO) &&
4743 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004744 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004745
4746 mpClientInterface->restoreOutput(a2dpOutput);
4747 mA2dpSuspended = false;
4748 }
4749 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004750 if (isScoConnected &&
4751 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4752 AUDIO_POLICY_FORCE_BT_SCO) ||
4753 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4754 AUDIO_POLICY_FORCE_BT_SCO) ||
4755 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004756 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004757
4758 mpClientInterface->suspendOutput(a2dpOutput);
4759 mA2dpSuspended = true;
4760 }
4761 }
4762}
4763
Eric Laurent97ac8712018-07-27 18:59:02 -07004764template <class IoDescriptor, class Filter>
4765sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4766 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4767{
4768 auto activeClients = desc->clientsList(true /*activeOnly*/);
4769 auto activeClientsWithRoute =
4770 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4771 active = activeClients.size() > 0;
4772 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4773 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4774 }
4775 return nullptr;
4776}
4777
4778template <class IoCollection, class Filter>
4779sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4780 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4781{
4782 sp<DeviceDescriptor> device;
4783 for (size_t i = 0; i < ioCollection.size(); i++) {
4784 auto desc = ioCollection.valueAt(i);
4785 bool active;
4786 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4787 if (active && curDevice == nullptr) {
4788 return nullptr;
4789 } else if (curDevice != nullptr) {
4790 device = curDevice;
4791 }
4792 }
4793 return device;
4794}
4795
Eric Laurentc75307b2015-03-17 15:29:32 -07004796audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4797 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004798{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004799 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 if (index >= 0) {
4801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4802 if (patchDesc->mUid != mUidCached) {
4803 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004804 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 return outputDesc->device();
4806 }
4807 }
4808
Eric Laurent97ac8712018-07-27 18:59:02 -07004809 // Honor explicit routing requests only if no client using default routing is active on this
4810 // input: a specific app can not force routing for other apps by setting a preferred device.
4811 bool active; // unused
4812 sp<DeviceDescriptor> deviceDesc =
4813 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4814 if (deviceDesc != nullptr) {
4815 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004816 }
4817
Eric Laurente552edb2014-03-10 17:42:56 -07004818 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004819 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004820 // use device for strategy enforced audible
4821 // 2: we are in call or the strategy phone is active on the output:
4822 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004823 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004824 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004825 // 4: the strategy for enforced audible is active but not enforced on the output:
4826 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004827 // 5: the strategy accessibility is active on the output:
4828 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004829 // 6: the strategy "respectful" sonification is active on the output:
4830 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004831 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004832 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004833 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004834 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004835 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004836 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004837
4838 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4839 // with a refined rule considering mutually exclusive devices (using same backend)
4840 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004841 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004842 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004843 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004844 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4845 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004846 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004847 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004848 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004849 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004850 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4851 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004852 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4853 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004854 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004855 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004856 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004857 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004858 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004859 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004860 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004861 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004862 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004864 }
4865
Eric Laurent1c333e22014-05-20 10:48:17 -07004866 ALOGV("getNewOutputDevice() selected device %x", device);
4867 return device;
4868}
4869
Eric Laurentfb66dd92016-01-28 18:32:03 -08004870audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004871{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004872 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004873
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004874 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 if (index >= 0) {
4876 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4877 if (patchDesc->mUid != mUidCached) {
4878 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004879 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004880 return inputDesc->mDevice;
4881 }
4882 }
4883
Eric Laurent97ac8712018-07-27 18:59:02 -07004884 // Honor explicit routing requests only if no client using default routing is active on this
4885 // input: a specific app can not force routing for other apps by setting a preferred device.
4886 bool active;
4887 sp<DeviceDescriptor> deviceDesc =
4888 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4889 if (deviceDesc != nullptr) {
4890 return deviceDesc->type();
4891 }
4892
Eric Laurentdc95a252018-04-12 12:46:56 -07004893 // If we are not in call and no client is active on this input, this methods returns
4894 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004895 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004896 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4897 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4898 }
4899 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004900 device = getDeviceAndMixForInputSource(source);
4901 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004902
Eric Laurente552edb2014-03-10 17:42:56 -07004903 return device;
4904}
4905
Eric Laurent794fde22016-03-11 09:50:45 -08004906bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4907 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004908 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004909}
4910
Eric Laurente0720872014-03-11 09:30:41 -07004911uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004912 return (uint32_t)getStrategy(stream);
4913}
4914
Eric Laurente0720872014-03-11 09:30:41 -07004915audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004916 // By checking the range of stream before calling getStrategy, we avoid
4917 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4918 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004919 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004920 return AUDIO_DEVICE_NONE;
4921 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004922 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004923 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004924 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4925 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004926 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 }
Eric Laurent794fde22016-03-11 09:50:45 -08004928 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004929 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004930 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004931 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004932 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4933 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004934 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004935 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004936 }
4937 }
Eric Laurente552edb2014-03-10 17:42:56 -07004938 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004939
Eric Laurentb0688d62018-08-14 15:49:18 -07004940 // Favor devices selected on active streams if any to report correct device in case of
4941 // explicit device selection
4942 if (activeDevices != AUDIO_DEVICE_NONE) {
4943 devices = activeDevices;
4944 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004945 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4946 and doesn't really need to.*/
4947 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4948 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4949 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4950 }
Eric Laurente552edb2014-03-10 17:42:56 -07004951 return devices;
4952}
4953
François Gaffie2110e042015-03-24 08:41:51 +01004954routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4955{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004956 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004957 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004958}
4959
Eric Laurent97ac8712018-07-27 18:59:02 -07004960routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004961 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004962 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004963 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004964 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004965 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004966 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004967 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004968 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004969 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004970}
4971
Eric Laurente0720872014-03-11 09:30:41 -07004972void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004973 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004974 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004975 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4976 updateDevicesAndOutputs();
4977 break;
4978 default:
4979 break;
4980 }
4981}
4982
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004983uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004984
4985 // skip beacon mute management if a dedicated TTS output is available
4986 if (mTtsOutputAvailable) {
4987 return 0;
4988 }
4989
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004990 switch(event) {
4991 case STARTING_OUTPUT:
4992 mBeaconMuteRefCount++;
4993 break;
4994 case STOPPING_OUTPUT:
4995 if (mBeaconMuteRefCount > 0) {
4996 mBeaconMuteRefCount--;
4997 }
4998 break;
4999 case STARTING_BEACON:
5000 mBeaconPlayingRefCount++;
5001 break;
5002 case STOPPING_BEACON:
5003 if (mBeaconPlayingRefCount > 0) {
5004 mBeaconPlayingRefCount--;
5005 }
5006 break;
5007 }
5008
5009 if (mBeaconMuteRefCount > 0) {
5010 // any playback causes beacon to be muted
5011 return setBeaconMute(true);
5012 } else {
5013 // no other playback: unmute when beacon starts playing, mute when it stops
5014 return setBeaconMute(mBeaconPlayingRefCount == 0);
5015 }
5016}
5017
5018uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5019 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5020 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5021 // keep track of muted state to avoid repeating mute/unmute operations
5022 if (mBeaconMuted != mute) {
5023 // mute/unmute AUDIO_STREAM_TTS on all outputs
5024 ALOGV("\t muting %d", mute);
5025 uint32_t maxLatency = 0;
5026 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005027 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005028 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005029 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005030 0 /*delay*/, AUDIO_DEVICE_NONE);
5031 const uint32_t latency = desc->latency() * 2;
5032 if (latency > maxLatency) {
5033 maxLatency = latency;
5034 }
5035 }
5036 mBeaconMuted = mute;
5037 return maxLatency;
5038 }
5039 return 0;
5040}
5041
Eric Laurente0720872014-03-11 09:30:41 -07005042audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005043 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005044{
Eric Laurent97ac8712018-07-27 18:59:02 -07005045 // Honor explicit routing requests only if all active clients have a preferred route in which
5046 // case the last active client route is used
5047 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5048 if (deviceDesc != nullptr) {
5049 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005050 }
5051
Eric Laurente552edb2014-03-10 17:42:56 -07005052 if (fromCache) {
5053 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5054 strategy, mDeviceForStrategy[strategy]);
5055 return mDeviceForStrategy[strategy];
5056 }
François Gaffie2110e042015-03-24 08:41:51 +01005057 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005058}
5059
Eric Laurente0720872014-03-11 09:30:41 -07005060void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005061{
5062 for (int i = 0; i < NUM_STRATEGIES; i++) {
5063 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5064 }
5065 mPreviousOutputs = mOutputs;
5066}
5067
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005068uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005069 audio_devices_t prevDevice,
5070 uint32_t delayMs)
5071{
5072 // mute/unmute strategies using an incompatible device combination
5073 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5074 // if unmuting, unmute only after the specified delay
5075 if (outputDesc->isDuplicated()) {
5076 return 0;
5077 }
5078
5079 uint32_t muteWaitMs = 0;
5080 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005081 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005082
5083 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5084 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005085 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005086 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5087 bool doMute = false;
5088
5089 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5090 doMute = true;
5091 outputDesc->mStrategyMutedByDevice[i] = true;
5092 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5093 doMute = true;
5094 outputDesc->mStrategyMutedByDevice[i] = false;
5095 }
Eric Laurent99401132014-05-07 19:48:15 -07005096 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005097 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005098 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005099 // skip output if it does not share any device with current output
5100 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5101 == AUDIO_DEVICE_NONE) {
5102 continue;
5103 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005104 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005105 mute ? "muting" : "unmuting", i, curDevice);
5106 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005107 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005108 if (mute) {
5109 // FIXME: should not need to double latency if volume could be applied
5110 // immediately by the audioflinger mixer. We must account for the delay
5111 // between now and the next time the audioflinger thread for this output
5112 // will process a buffer (which corresponds to one buffer size,
5113 // usually 1/2 or 1/4 of the latency).
5114 if (muteWaitMs < desc->latency() * 2) {
5115 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005116 }
5117 }
5118 }
5119 }
5120 }
5121 }
5122
Eric Laurent99401132014-05-07 19:48:15 -07005123 // temporary mute output if device selection changes to avoid volume bursts due to
5124 // different per device volumes
5125 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005126 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5127 // temporary mute duration is conservatively set to 4 times the reported latency
5128 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5129 if (muteWaitMs < tempMuteWaitMs) {
5130 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005131 }
Eric Laurentdc462862016-07-19 12:29:53 -07005132
Eric Laurent99401132014-05-07 19:48:15 -07005133 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005134 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005135 // make sure that we do not start the temporary mute period too early in case of
5136 // delayed device change
5137 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005138 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005139 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005140 }
5141 }
5142 }
5143
Eric Laurente552edb2014-03-10 17:42:56 -07005144 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5145 if (muteWaitMs > delayMs) {
5146 muteWaitMs -= delayMs;
5147 usleep(muteWaitMs * 1000);
5148 return muteWaitMs;
5149 }
5150 return 0;
5151}
5152
Eric Laurentc75307b2015-03-17 15:29:32 -07005153uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005154 audio_devices_t device,
5155 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005157 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005158 const char *address,
5159 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005160{
Eric Laurentc75307b2015-03-17 15:29:32 -07005161 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005162 AudioParameter param;
5163 uint32_t muteWaitMs;
5164
5165 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005166 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5167 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5168 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5169 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005170 return muteWaitMs;
5171 }
5172 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5173 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005174 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005175 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005176 return 0;
5177 }
5178
5179 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005181
5182 audio_devices_t prevDevice = outputDesc->mDevice;
5183
Paul McLeanaa981192015-03-21 09:55:15 -07005184 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005185
5186 if (device != AUDIO_DEVICE_NONE) {
5187 outputDesc->mDevice = device;
5188 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005189
5190 // if the outputs are not materially active, there is no need to mute.
5191 if (requiresMuteCheck) {
5192 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5193 } else {
5194 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5195 muteWaitMs = 0;
5196 }
Eric Laurente552edb2014-03-10 17:42:56 -07005197
5198 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005199 // the requested device is AUDIO_DEVICE_NONE
5200 // OR the requested device is the same as current device
5201 // AND force is not specified
5202 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005203 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005204 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5205 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005206 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005207 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005208 return muteWaitMs;
5209 }
5210
5211 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005212
Eric Laurente552edb2014-03-10 17:42:56 -07005213 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005214 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005215 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005216 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005217 DeviceVector deviceList;
5218 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005219 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005220 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005221 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5222 device, String8(address));
5223 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005224 }
5225
Eric Laurent1c333e22014-05-20 10:48:17 -07005226 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005227 PatchBuilder patchBuilder;
5228 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005229 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005230 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005231 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005232 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005234
5235 // inform all input as well
5236 for (size_t i = 0; i < mInputs.size(); i++) {
5237 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005238 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005239 AudioParameter inputCmd = AudioParameter();
5240 ALOGV("%s: inform input %d of device:%d", __func__,
5241 inputDescriptor->mIoHandle, device);
5242 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5243 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5244 inputCmd.toString(),
5245 delayMs);
5246 }
5247 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005248 }
Eric Laurente552edb2014-03-10 17:42:56 -07005249
5250 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005251 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005252
5253 return muteWaitMs;
5254}
5255
Eric Laurentc75307b2015-03-17 15:29:32 -07005256status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 int delayMs,
5258 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005259{
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 ssize_t index;
5261 if (patchHandle) {
5262 index = mAudioPatches.indexOfKey(*patchHandle);
5263 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005264 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 }
5266 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 return INVALID_OPERATION;
5268 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5270 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005271 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005272 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 removeAudioPatch(patchDesc->mHandle);
5274 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005275 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005276 return status;
5277}
5278
5279status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5280 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 bool force,
5282 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005283{
5284 status_t status = NO_ERROR;
5285
Eric Laurent1f2f2232014-06-02 12:01:23 -07005286 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005287 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5288 inputDesc->mDevice = device;
5289
Mikhail Naganov708e0382018-05-30 09:53:04 -07005290 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005291 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005292 PatchBuilder patchBuilder;
5293 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005294 // AUDIO_SOURCE_HOTWORD is for internal use only:
5295 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005296 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5297 auto result = usecase;
5298 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5299 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5300 }
5301 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005302 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005303 addSource(deviceList.itemAt(0));
5304 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005305 }
5306 }
5307 return status;
5308}
5309
Eric Laurent6a94d692014-05-20 11:18:06 -07005310status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5311 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005312{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005313 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 ssize_t index;
5315 if (patchHandle) {
5316 index = mAudioPatches.indexOfKey(*patchHandle);
5317 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005318 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 }
5320 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005321 return INVALID_OPERATION;
5322 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5324 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005326 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 removeAudioPatch(patchDesc->mHandle);
5328 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005329 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 return status;
5331}
5332
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005333sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005334 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005335 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005336 audio_format_t& format,
5337 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005338 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005339{
5340 // Choose an input profile based on the requested capture parameters: select the first available
5341 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005342 //
5343 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5344 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005345
Glenn Kasten730b9262018-03-29 15:01:26 -07005346 sp<IOProfile> firstInexact;
5347 uint32_t updatedSamplingRate = 0;
5348 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5349 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005350 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005351 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005352 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005353 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005354 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005355 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005356 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005357 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005358 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005359 &channelMask /*updatedChannelMask*/,
5360 // FIXME ugly cast
5361 (audio_output_flags_t) flags,
5362 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005363 return profile;
5364 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005365 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5366 samplingRate,
5367 &updatedSamplingRate,
5368 format,
5369 &updatedFormat,
5370 channelMask,
5371 &updatedChannelMask,
5372 // FIXME ugly cast
5373 (audio_output_flags_t) flags,
5374 false /*exactMatchRequiredForInputFlags*/)) {
5375 firstInexact = profile;
5376 }
5377
Eric Laurente552edb2014-03-10 17:42:56 -07005378 }
5379 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 if (firstInexact != nullptr) {
5381 samplingRate = updatedSamplingRate;
5382 format = updatedFormat;
5383 channelMask = updatedChannelMask;
5384 return firstInexact;
5385 }
Eric Laurente552edb2014-03-10 17:42:56 -07005386 return NULL;
5387}
5388
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005389
5390audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005391 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005392{
Eric Laurent97ac8712018-07-27 18:59:02 -07005393 // Honor explicit routing requests only if all active clients have a preferred route in which
5394 // case the last active client route is used
5395 sp<DeviceDescriptor> deviceDesc =
5396 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5397 if (deviceDesc != nullptr) {
5398 return deviceDesc->type();
5399 }
5400
5401
François Gaffie036e1e92015-03-19 10:16:24 +01005402 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5403 audio_devices_t selectedDeviceFromMix =
5404 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005405
François Gaffie036e1e92015-03-19 10:16:24 +01005406 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5407 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005408 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005409 return getDeviceForInputSource(inputSource);
5410}
5411
5412audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5413{
Eric Laurent97ac8712018-07-27 18:59:02 -07005414 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005415}
5416
Eric Laurente0720872014-03-11 09:30:41 -07005417float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005418 int index,
5419 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005420{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005421 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005422
5423 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5424 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5425 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5426 // the ringtone volume
5427 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5428 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5429 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5430 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5431 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5432 }
5433
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005434 // in-call: always cap volume by voice volume + some low headroom
5435 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005436 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005437 switch (stream) {
5438 case AUDIO_STREAM_SYSTEM:
5439 case AUDIO_STREAM_RING:
5440 case AUDIO_STREAM_MUSIC:
5441 case AUDIO_STREAM_ALARM:
5442 case AUDIO_STREAM_NOTIFICATION:
5443 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5444 case AUDIO_STREAM_DTMF:
5445 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005446 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005447 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005448 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005449 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005450 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005451 if (volumeDB > maxVoiceVolDb) {
5452 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5453 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5454 volumeDB = maxVoiceVolDb;
5455 }
5456 } break;
5457 default:
5458 break;
5459 }
5460 }
5461
Eric Laurente552edb2014-03-10 17:42:56 -07005462 // if a headset is connected, apply the following rules to ring tones and notifications
5463 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005464 // - always attenuate notifications volume by 6dB
5465 // - attenuate ring tones volume by 6dB unless music is not playing and
5466 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005467 // - if music is playing, always limit the volume to current music volume,
5468 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005469 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005470 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5471 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5472 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005473 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005474 AUDIO_DEVICE_OUT_USB_HEADSET |
5475 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005476 ((stream_strategy == STRATEGY_SONIFICATION)
5477 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005478 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005479 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005480 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005481 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005482 // when the phone is ringing we must consider that music could have been paused just before
5483 // by the music application and behave as if music was active if the last music track was
5484 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005485 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005486 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005488 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005490 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5491 musicDevice),
5492 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005493 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5494 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005495 if (volumeDB > minVolDB) {
5496 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005497 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005498 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005499 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5500 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5501 // on A2DP, also ensure notification volume is not too low compared to media when
5502 // intended to be played
5503 if ((volumeDB > -96.0f) &&
5504 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5505 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5506 stream, device,
5507 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5508 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5509 }
5510 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005511 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5512 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005513 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005514 }
5515 }
5516
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005517 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005518}
5519
Eric Laurent3839bc02018-07-10 18:33:34 -07005520int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5521 audio_stream_type_t srcStream,
5522 audio_stream_type_t dstStream)
5523{
5524 if (srcStream == dstStream) {
5525 return srcIndex;
5526 }
5527 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5528 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5529 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5530 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5531
5532 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5533}
5534
Eric Laurente0720872014-03-11 09:30:41 -07005535status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005536 int index,
5537 const sp<AudioOutputDescriptor>& outputDesc,
5538 audio_devices_t device,
5539 int delayMs,
5540 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005541{
Eric Laurente552edb2014-03-10 17:42:56 -07005542 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005543 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005544 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005546 return NO_ERROR;
5547 }
François Gaffie2110e042015-03-24 08:41:51 +01005548 audio_policy_forced_cfg_t forceUseForComm =
5549 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005550 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005551 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5552 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005553 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005554 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005555 return INVALID_OPERATION;
5556 }
5557
Eric Laurentc75307b2015-03-17 15:29:32 -07005558 if (device == AUDIO_DEVICE_NONE) {
5559 device = outputDesc->device();
5560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005561
Eric Laurentffbc80f2015-03-18 18:30:19 -07005562 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005563 if (outputDesc->isFixedVolume(device) ||
5564 // Force VoIP volume to max for bluetooth SCO
5565 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5566 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005567 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005568 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005569
Eric Laurentffbc80f2015-03-18 18:30:19 -07005570 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005571
Eric Laurent3b73df72014-03-11 09:06:29 -07005572 if (stream == AUDIO_STREAM_VOICE_CALL ||
5573 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005574 float voiceVolume;
5575 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005576 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005577 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005578 } else {
5579 voiceVolume = 1.0;
5580 }
5581
Eric Laurent18fba842016-03-31 14:41:26 -07005582 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005583 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5584 mLastVoiceVolume = voiceVolume;
5585 }
5586 }
5587
5588 return NO_ERROR;
5589}
5590
Eric Laurentc75307b2015-03-17 15:29:32 -07005591void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5592 audio_devices_t device,
5593 int delayMs,
5594 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005595{
Eric Laurentc75307b2015-03-17 15:29:32 -07005596 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005597
Eric Laurent794fde22016-03-11 09:50:45 -08005598 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005600 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005602 device,
5603 delayMs,
5604 force);
5605 }
5606}
5607
Eric Laurente0720872014-03-11 09:30:41 -07005608void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005609 bool on,
5610 const sp<AudioOutputDescriptor>& outputDesc,
5611 int delayMs,
5612 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005613{
Eric Laurent72249d52015-06-08 11:12:15 -07005614 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5615 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005616 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005617 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005619 }
5620 }
5621}
5622
Eric Laurente0720872014-03-11 09:30:41 -07005623void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005624 bool on,
5625 const sp<AudioOutputDescriptor>& outputDesc,
5626 int delayMs,
5627 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005628{
Eric Laurente552edb2014-03-10 17:42:56 -07005629 if (device == AUDIO_DEVICE_NONE) {
5630 device = outputDesc->device();
5631 }
5632
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5634 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005635
5636 if (on) {
5637 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005638 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005640 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005641 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005642 }
5643 }
5644 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5645 outputDesc->mMuteCount[stream]++;
5646 } else {
5647 if (outputDesc->mMuteCount[stream] == 0) {
5648 ALOGV("setStreamMute() unmuting non muted stream!");
5649 return;
5650 }
5651 if (--outputDesc->mMuteCount[stream] == 0) {
5652 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005653 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005654 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005655 device,
5656 delayMs);
5657 }
5658 }
5659}
5660
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005661audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5662{
5663 // flags to stream type mapping
5664 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5665 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5666 }
5667 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5668 return AUDIO_STREAM_BLUETOOTH_SCO;
5669 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005670 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5671 return AUDIO_STREAM_TTS;
5672 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005673
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005674 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005675}
Eric Laurente83b55d2014-11-14 10:06:21 -08005676
François Gaffie53615e22015-03-19 09:24:12 +01005677bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5678{
Eric Laurente83b55d2014-11-14 10:06:21 -08005679 // has flags that map to a strategy?
5680 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5681 return true;
5682 }
5683
5684 // has known usage?
5685 switch (paa->usage) {
5686 case AUDIO_USAGE_UNKNOWN:
5687 case AUDIO_USAGE_MEDIA:
5688 case AUDIO_USAGE_VOICE_COMMUNICATION:
5689 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5690 case AUDIO_USAGE_ALARM:
5691 case AUDIO_USAGE_NOTIFICATION:
5692 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5693 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5694 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5695 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5696 case AUDIO_USAGE_NOTIFICATION_EVENT:
5697 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5698 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5699 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5700 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005701 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005702 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005703 break;
5704 default:
5705 return false;
5706 }
5707 return true;
5708}
5709
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005710bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005711 routing_strategy strategy, uint32_t inPastMs,
5712 nsecs_t sysTime) const
5713{
5714 if ((sysTime == 0) && (inPastMs != 0)) {
5715 sysTime = systemTime();
5716 }
Eric Laurent794fde22016-03-11 09:50:45 -08005717 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005718 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005719 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005720 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5721 return true;
5722 }
5723 }
5724 return false;
5725}
5726
Eric Laurent484e9272018-06-07 17:29:23 -07005727bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5728 routing_strategy strategy, uint32_t inPastMs,
5729 nsecs_t sysTime) const
5730{
5731 for (size_t i = 0; i < mOutputs.size(); i++) {
5732 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5733 if (outputDesc->sharesHwModuleWith(desc)
5734 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5735 return true;
5736 }
5737 }
5738 return false;
5739}
5740
François Gaffie2110e042015-03-24 08:41:51 +01005741audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5742{
5743 return mEngine->getForceUse(usage);
5744}
5745
5746bool AudioPolicyManager::isInCall()
5747{
5748 return isStateInCall(mEngine->getPhoneState());
5749}
5750
5751bool AudioPolicyManager::isStateInCall(int state)
5752{
5753 return is_state_in_call(state);
5754}
5755
Eric Laurentd60560a2015-04-10 11:31:20 -07005756void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5757{
5758 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005759 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5760 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5761 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5762 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005763 }
5764 }
5765
5766 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5767 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5768 bool release = false;
5769 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5770 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5771 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5772 source->ext.device.type == deviceDesc->type()) {
5773 release = true;
5774 }
5775 }
5776 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5777 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5778 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5779 sink->ext.device.type == deviceDesc->type()) {
5780 release = true;
5781 }
5782 }
5783 if (release) {
5784 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5785 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5786 }
5787 }
5788}
5789
Phil Burk09bc4612016-02-24 15:58:15 -08005790// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005791void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5792 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005793 // TODO Set this based on Config properties.
5794 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005795
5796 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5797 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005798 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005799
jiabin81772902018-04-02 17:52:27 -07005800 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5801 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5802 formats.clear();
5803 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5804 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005805 }
jiabin81772902018-04-02 17:52:27 -07005806 // Always enable IEC61937 when in MANUAL mode.
5807 formats.add(AUDIO_FORMAT_IEC61937);
5808 } else { // NEVER, AUTO or ALWAYS
5809 // Analyze original support for various formats.
5810 bool supportsAC3 = false;
5811 bool supportsOtherSurround = false;
5812 bool supportsIEC61937 = false;
5813 mSurroundFormats.clear();
5814 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5815 audio_format_t format = formats[formatIndex];
5816 switch (format) {
5817 case AUDIO_FORMAT_AC3:
5818 supportsAC3 = true;
5819 break;
5820 case AUDIO_FORMAT_E_AC3:
5821 case AUDIO_FORMAT_DTS:
5822 case AUDIO_FORMAT_DTS_HD:
5823 // If ALWAYS, remove all other surround formats here
5824 // since we will add them later.
5825 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5826 formats.removeAt(formatIndex);
5827 formatIndex--;
5828 }
5829 supportsOtherSurround = true;
5830 break;
5831 case AUDIO_FORMAT_IEC61937:
5832 supportsIEC61937 = true;
5833 break;
5834 default:
5835 break;
5836 }
5837 }
Phil Burk09bc4612016-02-24 15:58:15 -08005838
jiabin81772902018-04-02 17:52:27 -07005839 // Modify formats based on surround preferences.
5840 // If NEVER, remove support for surround formats.
5841 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5842 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5843 // Remove surround sound related formats.
5844 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5845 audio_format_t format = formats[formatIndex];
5846 switch(format) {
5847 case AUDIO_FORMAT_AC3:
5848 case AUDIO_FORMAT_E_AC3:
5849 case AUDIO_FORMAT_DTS:
5850 case AUDIO_FORMAT_DTS_HD:
5851 case AUDIO_FORMAT_IEC61937:
5852 formats.removeAt(formatIndex);
5853 break;
5854 default:
5855 formatIndex++; // keep it
5856 break;
5857 }
5858 }
5859 supportsAC3 = false;
5860 supportsOtherSurround = false;
5861 supportsIEC61937 = false;
5862 }
5863 } else { // AUTO or ALWAYS
5864 // Most TVs support AC3 even if they do not report it in the EDID.
5865 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5866 && !supportsAC3) {
5867 formats.add(AUDIO_FORMAT_AC3);
5868 supportsAC3 = true;
5869 }
5870
5871 // If ALWAYS, add support for raw surround formats if all are missing.
5872 // This assumes that if any of these formats are reported by the HAL
5873 // then the report is valid and should not be modified.
5874 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5875 formats.add(AUDIO_FORMAT_E_AC3);
5876 formats.add(AUDIO_FORMAT_DTS);
5877 formats.add(AUDIO_FORMAT_DTS_HD);
5878 supportsOtherSurround = true;
5879 }
5880
5881 // Add support for IEC61937 if any raw surround supported.
5882 // The HAL could do this but add it here, just in case.
5883 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5884 formats.add(AUDIO_FORMAT_IEC61937);
5885 supportsIEC61937 = true;
5886 }
5887
5888 // Add reported surround sound formats to enabled surround formats.
5889 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005890 audio_format_t format = formats[formatIndex];
5891 switch(format) {
5892 case AUDIO_FORMAT_AC3:
5893 case AUDIO_FORMAT_E_AC3:
5894 case AUDIO_FORMAT_DTS:
5895 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005896 case AUDIO_FORMAT_AAC_LC:
5897 case AUDIO_FORMAT_DOLBY_TRUEHD:
5898 case AUDIO_FORMAT_E_AC3_JOC:
5899 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005900 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005901 break;
5902 }
Phil Burk09bc4612016-02-24 15:58:15 -08005903 }
Phil Burk07ac1142016-03-25 13:39:29 -07005904 }
Phil Burk09bc4612016-02-24 15:58:15 -08005905 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005906}
5907
5908// Modify the list of channel masks supported.
5909void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5910 ChannelsVector &channelMasks = *channelMasksPtr;
5911 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5912 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5913
5914 // If NEVER, then remove support for channelMasks > stereo.
5915 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5916 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5917 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5918 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5919 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5920 channelMasks.removeAt(maskIndex);
5921 } else {
5922 maskIndex++;
5923 }
5924 }
jiabin81772902018-04-02 17:52:27 -07005925 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5926 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5927 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005928 bool supports5dot1 = false;
5929 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005930 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005931 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5932 supports5dot1 = true;
5933 break;
5934 }
5935 }
5936 // If not then add 5.1 support.
5937 if (!supports5dot1) {
5938 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5939 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5940 }
Phil Burk09bc4612016-02-24 15:58:15 -08005941 }
5942}
5943
Phil Burk00eeb322016-03-31 12:41:00 -07005944void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5945 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005946 AudioProfileVector &profiles)
5947{
5948 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005949
François Gaffie112b0af2015-11-19 16:13:25 +01005950 // Format MUST be checked first to update the list of AudioProfile
5951 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005952 reply = mpClientInterface->getParameters(
5953 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005954 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005955 AudioParameter repliedParameters(reply);
5956 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005957 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005958 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5959 return;
5960 }
Phil Burk09bc4612016-02-24 15:58:15 -08005961 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005962 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005963 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005964 }
Phil Burk09bc4612016-02-24 15:58:15 -08005965 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005966 }
François Gaffie112b0af2015-11-19 16:13:25 +01005967
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005968 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005969 ChannelsVector channelMasks;
5970 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005971 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005972 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005973
5974 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005975 reply = mpClientInterface->getParameters(
5976 ioHandle,
5977 requestedParameters.toString() + ";" +
5978 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005979 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005980 AudioParameter repliedParameters(reply);
5981 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005982 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005983 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005984 }
5985 }
5986 if (profiles.hasDynamicChannelsFor(format)) {
5987 reply = mpClientInterface->getParameters(ioHandle,
5988 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005989 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005990 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005991 AudioParameter repliedParameters(reply);
5992 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005993 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005994 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005995 if (device == AUDIO_DEVICE_OUT_HDMI) {
5996 filterSurroundChannelMasks(&channelMasks);
5997 }
François Gaffie112b0af2015-11-19 16:13:25 +01005998 }
5999 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006000 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006001 }
6002}
Eric Laurentd60560a2015-04-10 11:31:20 -07006003
Mikhail Naganovdc769682018-05-04 15:34:08 -07006004status_t AudioPolicyManager::installPatch(const char *caller,
6005 audio_patch_handle_t *patchHandle,
6006 AudioIODescriptorInterface *ioDescriptor,
6007 const struct audio_patch *patch,
6008 int delayMs)
6009{
6010 ssize_t index = mAudioPatches.indexOfKey(
6011 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6012 *patchHandle : ioDescriptor->getPatchHandle());
6013 sp<AudioPatch> patchDesc;
6014 status_t status = installPatch(
6015 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6016 if (status == NO_ERROR) {
6017 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6018 }
6019 return status;
6020}
6021
6022status_t AudioPolicyManager::installPatch(const char *caller,
6023 ssize_t index,
6024 audio_patch_handle_t *patchHandle,
6025 const struct audio_patch *patch,
6026 int delayMs,
6027 uid_t uid,
6028 sp<AudioPatch> *patchDescPtr)
6029{
6030 sp<AudioPatch> patchDesc;
6031 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6032 if (index >= 0) {
6033 patchDesc = mAudioPatches.valueAt(index);
6034 afPatchHandle = patchDesc->mAfPatchHandle;
6035 }
6036
6037 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6038 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6039 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6040 if (status == NO_ERROR) {
6041 if (index < 0) {
6042 patchDesc = new AudioPatch(patch, uid);
6043 addAudioPatch(patchDesc->mHandle, patchDesc);
6044 } else {
6045 patchDesc->mPatch = *patch;
6046 }
6047 patchDesc->mAfPatchHandle = afPatchHandle;
6048 if (patchHandle) {
6049 *patchHandle = patchDesc->mHandle;
6050 }
6051 nextAudioPortGeneration();
6052 mpClientInterface->onAudioPatchListUpdate();
6053 }
6054 if (patchDescPtr) *patchDescPtr = patchDesc;
6055 return status;
6056}
6057
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006058} // namespace android