blob: 18c5567b28ba16db5ccf00446c996cfbf54043a5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070040
François Gaffie2110e042015-03-24 08:41:51 +010041#include <AudioPolicyManagerInterface.h>
42#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070048#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070050#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010053#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010054#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010055#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010056#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010057#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010058#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Eric Laurentdc462862016-07-19 12:29:53 -070062//FIXME: workaround for truncated touch sounds
63// to be removed when the problem is handled by system UI
64#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070065
66// Largest difference in dB on earpiece in call between the voice volume and another
67// media / notification / system volume.
68constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
69
Mikhail Naganov15be9d22017-11-08 14:18:13 +110070// Compressed formats for MSD module, ordered from most preferred to least preferred.
71static const std::vector<audio_format_t> compressedFormatsOrder = {{
72 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
73 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
74// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
75static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
76 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
77 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
78 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
79
Eric Laurente552edb2014-03-10 17:42:56 -070080// ----------------------------------------------------------------------------
81// AudioPolicyInterface implementation
82// ----------------------------------------------------------------------------
83
Eric Laurente0720872014-03-11 09:30:41 -070084status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080085 audio_policy_dev_state_t state,
86 const char *device_address,
87 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070088{
jiabina7b43792018-02-15 16:04:46 -080089 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
90 nextAudioPortGeneration();
91 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080092}
93
François Gaffie44481e72016-04-20 07:49:57 +020094void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
95 audio_policy_dev_state_t state,
96 const String8 &device_address)
97{
98 AudioParameter param(device_address);
99 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700100 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200101 param.addInt(key, device);
102 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
103}
104
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800105status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800106 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800107 const char *device_address,
108 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109{
Paul McLeane743a472015-01-28 11:07:31 -0800110 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800111 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700112
113 // connect/disconnect only 1 device at a time
114 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
115
François Gaffie53615e22015-03-19 09:24:12 +0100116 sp<DeviceDescriptor> devDesc =
117 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800118
Eric Laurente552edb2014-03-10 17:42:56 -0700119 // handle output devices
120 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700121 SortedVector <audio_io_handle_t> outputs;
122
Eric Laurent3a4311c2014-03-17 12:00:47 -0700123 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
124
Eric Laurente552edb2014-03-10 17:42:56 -0700125 // save a copy of the opened output descriptors before any output is opened or closed
126 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
127 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700128 switch (state)
129 {
130 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800131 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700132 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700133 ALOGW("setDeviceConnectionState() device already connected: %x", device);
134 return INVALID_OPERATION;
135 }
136 ALOGV("setDeviceConnectionState() connecting device %x", device);
137
Eric Laurente552edb2014-03-10 17:42:56 -0700138 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700139 index = mAvailableOutputDevices.add(devDesc);
140 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100141 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700142 if (module == 0) {
143 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
144 device);
145 mAvailableOutputDevices.remove(devDesc);
146 return INVALID_OPERATION;
147 }
Paul McLeane743a472015-01-28 11:07:31 -0800148 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 } else {
150 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700151 }
152
François Gaffie44481e72016-04-20 07:49:57 +0200153 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
154 // parameters on newly connected devices (instead of opening the outputs...)
155 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
156
Eric Laurenta1d525f2015-01-29 13:36:45 -0800157 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700158 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200159
160 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
161 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700162 return INVALID_OPERATION;
163 }
François Gaffie2110e042015-03-24 08:41:51 +0100164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
166
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 // outputs should never be empty here
168 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
169 "checkOutputsForDevice() returned no outputs but status OK");
170 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
171 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800172
Eric Laurent3ae5f312015-02-03 17:12:08 -0800173 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700174 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700175 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700176 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700177 ALOGW("setDeviceConnectionState() device not connected: %x", device);
178 return INVALID_OPERATION;
179 }
180
Paul McLean5c477aa2014-08-20 16:47:57 -0700181 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
182
Paul McLeane743a472015-01-28 11:07:31 -0800183 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200184 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700185
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700187 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700188
Eric Laurenta1d525f2015-01-29 13:36:45 -0800189 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100190
191 // Propagate device availability to Engine
192 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700193 } break;
194
195 default:
196 ALOGE("setDeviceConnectionState() invalid state: %x", state);
197 return BAD_VALUE;
198 }
199
Mikhail Naganov37977152018-07-11 15:54:44 -0700200 checkForDeviceAndOutputChanges([&]() {
201 // outputs must be closed after checkOutputForAllStrategies() is executed
202 if (!outputs.isEmpty()) {
203 for (audio_io_handle_t output : outputs) {
204 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
205 // close unused outputs after device disconnection or direct outputs that have been
206 // opened by checkOutputsForDevice() to query dynamic parameters
207 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
208 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
209 (desc->mDirectOpenCount == 0))) {
210 closeOutput(output);
211 }
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
214 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700215 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700216 return false;
217 });
Eric Laurente552edb2014-03-10 17:42:56 -0700218
Eric Laurent87ffa392015-05-22 10:32:38 -0700219 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700220 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
221 updateCallRouting(newDevice);
222 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100223 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700224 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700225 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
226 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
227 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700228 // do not force device change on duplicated output because if device is 0, it will
229 // also force a device 0 for the two outputs it is duplicated to which may override
230 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100231 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
232 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100233 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700234 // always force when disconnecting (a non-duplicated device)
235 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700236 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 }
Eric Laurente552edb2014-03-10 17:42:56 -0700238 }
239
Eric Laurentd60560a2015-04-10 11:31:20 -0700240 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
241 cleanUpForDevice(devDesc);
242 }
243
Eric Laurent72aa32f2014-05-30 18:51:48 -0700244 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700245 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700246 } // end if is output device
247
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // handle input devices
249 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700250 SortedVector <audio_io_handle_t> inputs;
251
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700253 switch (state)
254 {
255 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700256 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700258 ALOGW("setDeviceConnectionState() device already connected: %d", device);
259 return INVALID_OPERATION;
260 }
François Gaffie53615e22015-03-19 09:24:12 +0100261 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700262 if (module == NULL) {
263 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
264 device);
265 return INVALID_OPERATION;
266 }
François Gaffie44481e72016-04-20 07:49:57 +0200267
268 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
269 // parameters on newly connected devices (instead of opening the inputs...)
270 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
271
Paul McLean9080a4c2015-06-18 08:24:02 -0700272 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200273 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
274 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700275 return INVALID_OPERATION;
276 }
277
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 index = mAvailableInputDevices.add(devDesc);
279 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800280 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 } else {
282 return NO_MEMORY;
283 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800284
François Gaffie2110e042015-03-24 08:41:51 +0100285 // Propagate device availability to Engine
286 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700287 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700288
289 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700290 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700291 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700292 ALOGW("setDeviceConnectionState() device not connected: %d", device);
293 return INVALID_OPERATION;
294 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700295
296 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
297
298 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200299 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700300
Paul McLean9080a4c2015-06-18 08:24:02 -0700301 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
François Gaffie2110e042015-03-24 08:41:51 +0100304 // Propagate device availability to Engine
305 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700306 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700307
308 default:
309 ALOGE("setDeviceConnectionState() invalid state: %x", state);
310 return BAD_VALUE;
311 }
312
Eric Laurentd4692962014-05-05 18:13:44 -0700313 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700314 // As the input device list can impact the output device selection, update
315 // getDeviceForStrategy() cache
316 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700317
Eric Laurent87ffa392015-05-22 10:32:38 -0700318 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700319 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
320 updateCallRouting(newDevice);
321 }
322
Eric Laurentd60560a2015-04-10 11:31:20 -0700323 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
324 cleanUpForDevice(devDesc);
325 }
326
Eric Laurentb52c1522014-05-20 11:27:36 -0700327 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700329 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700330
331 ALOGW("setDeviceConnectionState() invalid device: %x", device);
332 return BAD_VALUE;
333}
334
Eric Laurente0720872014-03-11 09:30:41 -0700335audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100336 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700337{
Eric Laurent634b7142016-04-20 13:48:02 -0700338 sp<DeviceDescriptor> devDesc =
339 mHwModules.getDeviceDescriptor(device, device_address, "",
340 (strlen(device_address) != 0)/*matchAddress*/);
341
342 if (devDesc == 0) {
343 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
344 device, device_address);
345 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
346 }
François Gaffie53615e22015-03-19 09:24:12 +0100347
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 DeviceVector *deviceVector;
349
Eric Laurente552edb2014-03-10 17:42:56 -0700350 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700352 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 deviceVector = &mAvailableInputDevices;
354 } else {
355 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
356 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700357 }
Eric Laurent634b7142016-04-20 13:48:02 -0700358
359 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
360 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800361}
362
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800363status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
364 const char *device_address,
365 const char *device_name)
366{
367 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700368 String8 reply;
369 AudioParameter param;
370 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800371
372 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
373 device, device_address, device_name);
374
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800375 // connect/disconnect only 1 device at a time
376 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
377
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800378 // Check if the device is currently connected
379 sp<DeviceDescriptor> devDesc =
380 mHwModules.getDeviceDescriptor(device, device_address, device_name);
381 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
382 if (index < 0) {
383 // Nothing to do: device is not connected
384 return NO_ERROR;
385 }
386
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700387 // For offloaded A2DP, Hw modules may have the capability to
388 // configure codecs. Check if any of the loaded hw modules
389 // supports this.
390 // If supported, send a set parameter to configure A2DP codecs
391 // and return. No need to toggle device state.
392 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
393 reply = mpClientInterface->getParameters(
394 AUDIO_IO_HANDLE_NONE,
395 String8(AudioParameter::keyReconfigA2dpSupported));
396 AudioParameter repliedParameters(reply);
397 repliedParameters.getInt(
398 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
399 if (isReconfigA2dpSupported) {
400 const String8 key(AudioParameter::keyReconfigA2dp);
401 param.add(key, String8("true"));
402 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
403 return NO_ERROR;
404 }
405 }
406
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800407 // Toggle the device state: UNAVAILABLE -> AVAILABLE
408 // This will force reading again the device configuration
409 status = setDeviceConnectionState(device,
410 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
411 device_address, device_name);
412 if (status != NO_ERROR) {
413 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
414 status);
415 return status;
416 }
417
418 status = setDeviceConnectionState(device,
419 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
420 device_address, device_name);
421 if (status != NO_ERROR) {
422 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
423 status);
424 return status;
425 }
426
427 return NO_ERROR;
428}
429
Eric Laurentdc462862016-07-19 12:29:53 -0700430uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700431{
432 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700433 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434
Andy Hunga76c7de2016-12-13 19:14:31 -0800435 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700436 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700437 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800438 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700439 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
440
441 // release existing RX patch if any
442 if (mCallRxPatch != 0) {
443 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
444 mCallRxPatch.clear();
445 }
446 // release TX patch if any
447 if (mCallTxPatch != 0) {
448 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
449 mCallTxPatch.clear();
450 }
451
452 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
453 // via setOutputDevice() on primary output.
454 // Otherwise, create two audio patches for TX and RX path.
455 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700456 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700457 // If the TX device is also on the primary HW module, setOutputDevice() will take care
458 // of it due to legacy implementation. If not, create a patch.
459 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
460 == AUDIO_DEVICE_NONE) {
461 createTxPatch = true;
462 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700463 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800464 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700465 createTxPatch = true;
466 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700467 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800468 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 return muteWaitMs;
472}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
475 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700476 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478 sp<DeviceDescriptor> txSourceDeviceDesc;
479 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700480 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
481 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700483 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
484 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 }
486
487 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
488 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
489 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
490 // request to reuse existing output stream if one is already opened to reach the target device
491 if (output != AUDIO_IO_HANDLE_NONE) {
492 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
493 ALOG_ASSERT(!outputDesc->isDuplicated(),
494 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700495 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800496 }
497
498 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700499 // terminate active capture if on the same HW module as the call TX source device
500 // FIXME: would be better to refine to only inputs whose profile connects to the
501 // call TX device but this information is not in the audio patch and logic here must be
502 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800503 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800504 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700505 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700506 }
507 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700508 }
Eric Laurentdc462862016-07-19 12:29:53 -0700509
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800510 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700511 status_t status = mpClientInterface->createAudioPatch(
512 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 ALOGW_IF(status != NO_ERROR,
514 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
515 sp<AudioPatch> audioPatch;
516 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700517 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800518 audioPatch->mAfPatchHandle = afPatchHandle;
519 audioPatch->mUid = mUidCached;
520 }
521 return audioPatch;
522}
523
Mikhail Naganovdc769682018-05-04 15:34:08 -0700524sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100525 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700526 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 ALOG_ASSERT(!deviceList.isEmpty(),
528 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700529 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700530}
531
Eric Laurente0720872014-03-11 09:30:41 -0700532void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700533{
534 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100535 // store previous phone state for management of sonification strategy below
536 int oldState = mEngine->getPhoneState();
537
538 if (mEngine->setPhoneState(state) != NO_ERROR) {
539 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700540 return;
541 }
François Gaffie2110e042015-03-24 08:41:51 +0100542 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700544 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700545 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800546 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 }
548
François Gaffie2110e042015-03-24 08:41:51 +0100549 /**
550 * Switching to or from incall state or switching between telephony and VoIP lead to force
551 * routing command.
552 */
553 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
554 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700555
556 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700557 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700558
Eric Laurente552edb2014-03-10 17:42:56 -0700559 int delayMs = 0;
560 if (isStateInCall(state)) {
561 nsecs_t sysTime = systemTime();
562 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 // mute media and sonification strategies and delay device switch by the largest
565 // latency of any output where either strategy is active.
566 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100567 if ((isStrategyActive(desc, STRATEGY_MEDIA,
568 SONIFICATION_HEADSET_MUSIC_DELAY,
569 sysTime) ||
570 isStrategyActive(desc, STRATEGY_SONIFICATION,
571 SONIFICATION_HEADSET_MUSIC_DELAY,
572 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 (delayMs < (int)desc->latency()*2)) {
574 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 setStrategyMute(STRATEGY_MEDIA, true, desc);
577 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700578 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
580 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700581 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
582 }
583 }
584
Eric Laurent87ffa392015-05-22 10:32:38 -0700585 if (hasPrimaryOutput()) {
586 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
587 // the device returned is not necessarily reachable via this output
588 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
589 // force routing command to audio hardware when ending call
590 // even if no device change is needed
591 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
592 rxDevice = mPrimaryOutput->device();
593 }
Eric Laurente552edb2014-03-10 17:42:56 -0700594
Eric Laurent87ffa392015-05-22 10:32:38 -0700595 if (state == AUDIO_MODE_IN_CALL) {
596 updateCallRouting(rxDevice, delayMs);
597 } else if (oldState == AUDIO_MODE_IN_CALL) {
598 if (mCallRxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
600 mCallRxPatch.clear();
601 }
602 if (mCallTxPatch != 0) {
603 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
604 mCallTxPatch.clear();
605 }
606 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
607 } else {
608 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700611
612 // reevaluate routing on all outputs in case tracks have been started during the call
613 for (size_t i = 0; i < mOutputs.size(); i++) {
614 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
615 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
616 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800617 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700618 }
619 }
620
Eric Laurente552edb2014-03-10 17:42:56 -0700621 if (isStateInCall(state)) {
622 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700623 // force reevaluating accessibility routing when call starts
624 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700625 }
626
627 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700628 if (state == AUDIO_MODE_RINGTONE &&
629 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700630 mLimitRingtoneVolume = true;
631 } else {
632 mLimitRingtoneVolume = false;
633 }
634}
635
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700636audio_mode_t AudioPolicyManager::getPhoneState() {
637 return mEngine->getPhoneState();
638}
639
Eric Laurente0720872014-03-11 09:30:41 -0700640void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700641 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700642{
François Gaffie2110e042015-03-24 08:41:51 +0100643 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700644 if (config == mEngine->getForceUse(usage)) {
645 return;
646 }
Eric Laurente552edb2014-03-10 17:42:56 -0700647
François Gaffie2110e042015-03-24 08:41:51 +0100648 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
649 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
650 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700651 }
François Gaffie2110e042015-03-24 08:41:51 +0100652 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
653 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
654 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700655
656 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700657 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800658
Eric Laurentdc462862016-07-19 12:29:53 -0700659 //FIXME: workaround for truncated touch sounds
660 // to be removed when the problem is handled by system UI
661 uint32_t delayMs = 0;
662 uint32_t waitMs = 0;
663 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
664 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
665 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700666 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700667 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700668 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669 }
Eric Laurente552edb2014-03-10 17:42:56 -0700670 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700671 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
672 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
673 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700674 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
675 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676 }
Eric Laurente552edb2014-03-10 17:42:56 -0700677 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700678 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700679 }
680 }
681
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800682 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800683 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 if (activeDesc->mProfile->getSupportedDevices().types() &
686 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
687 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700688 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800689 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700690 }
Eric Laurente552edb2014-03-10 17:42:56 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692}
693
Eric Laurente0720872014-03-11 09:30:41 -0700694void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700695{
696 ALOGV("setSystemProperty() property %s, value %s", property, value);
697}
698
699// Find a direct output profile compatible with the parameters passed, even if the input flags do
700// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800701sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700702 audio_devices_t device,
703 uint32_t samplingRate,
704 audio_format_t format,
705 audio_channel_mask_t channelMask,
706 audio_output_flags_t flags)
707{
Eric Laurent861a6282015-05-18 15:40:16 -0700708 // only retain flags that will drive the direct output profile selection
709 // if explicitly requested
710 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700711 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
712 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700713 flags =
714 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
715
716 sp<IOProfile> profile;
717
Mikhail Naganovd4120142017-12-06 15:49:22 -0800718 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800719 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700720 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700721 samplingRate, NULL /*updatedSamplingRate*/,
722 format, NULL /*updatedFormat*/,
723 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700724 flags)) {
725 continue;
726 }
727 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 continue;
734 }
735 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100736 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700737 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700738 }
Eric Laurente552edb2014-03-10 17:42:56 -0700739 }
740 }
Eric Laurent861a6282015-05-18 15:40:16 -0700741 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700742}
743
Eric Laurentf4e63452017-11-06 19:31:46 +0000744audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700745{
Eric Laurent3b73df72014-03-11 09:06:29 -0700746 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700747 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800748
749 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
750 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
751 // format, flags, etc. This may result in some discrepancy for functions that utilize
752 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
753 // and AudioSystem::getOutputSamplingRate().
754
Eric Laurentf4e63452017-11-06 19:31:46 +0000755 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
756 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700757
Eric Laurentf4e63452017-11-06 19:31:46 +0000758 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
759 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700760}
761
Eric Laurente83b55d2014-11-14 10:06:21 -0800762status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
763 audio_io_handle_t *output,
764 audio_session_t session,
765 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700766 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800767 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200768 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700769 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800770 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700771{
Eric Laurente83b55d2014-11-14 10:06:21 -0800772 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700773 DeviceVector outputDevices;
774 routing_strategy strategy;
775 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700776 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100777 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700778
Eric Laurent8f42ea12018-08-08 09:08:25 -0700779 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
780 if (*portId != AUDIO_PORT_HANDLE_NONE) {
781 return INVALID_OPERATION;
782 }
783
Eric Laurente83b55d2014-11-14 10:06:21 -0800784 if (attr != NULL) {
785 if (!isValidAttributes(attr)) {
786 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
787 attr->usage, attr->content_type, attr->flags,
788 attr->tags);
789 return BAD_VALUE;
790 }
791 attributes = *attr;
792 } else {
793 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
794 ALOGE("getOutputForAttr(): invalid stream type");
795 return BAD_VALUE;
796 }
797 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700798 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800799
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700800 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700801 " session %d selectedDeviceId %d",
802 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
803 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700804
Eric Laurent97ac8712018-07-27 18:59:02 -0700805 *stream = streamTypefromAttributesInt(&attributes);
806
807 strategy = getStrategyForAttr(&attributes);
808
Scott Randolph7b1fd232018-06-18 15:33:03 -0700809 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700810 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
811 sp<DeviceDescriptor> deviceDesc =
812 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
813 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700814 } else {
815 // If no explict route, is there a matching dynamic policy that applies?
816 sp<SwAudioOutputDescriptor> desc;
817 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
818 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
819 if (!audio_has_proportional_frames(config->format)) {
820 return BAD_VALUE;
821 }
822 *stream = streamTypefromAttributesInt(&attributes);
823 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700824 AudioMix *mix = desc->mPolicyMix;
825 sp<DeviceDescriptor> deviceDesc =
826 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
827 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700828 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700829 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700830 }
831
832 // Virtual sources must always be dynamicaly or explicitly routed
833 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
834 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
835 return BAD_VALUE;
836 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700837 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700838 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700839
Eric Laurente83b55d2014-11-14 10:06:21 -0800840 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200841 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700842 }
843
Nadav Barb2f18162018-07-18 13:01:53 +0300844 // Set incall music only if device was explicitly set, and fallback to the device which is
845 // chosen by the engine if not.
846 // FIXME: provide a more generic approach which is not device specific and move this back
847 // to getOutputForDevice.
848 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
849 *stream == AUDIO_STREAM_MUSIC &&
850 audio_is_linear_pcm(config->format) &&
851 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300853 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
854 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700855 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300856 device = mEngine->getDeviceForStrategy(strategy);
857 }
858 }
859
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800860 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
861 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200862 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100864 *output = AUDIO_IO_HANDLE_NONE;
865 if (msdDevice != AUDIO_DEVICE_NONE) {
866 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
867 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
868 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
869 __func__, msdDevice, device);
870 device = msdDevice;
871 } else {
872 *output = AUDIO_IO_HANDLE_NONE;
873 }
874 }
875 if (*output == AUDIO_IO_HANDLE_NONE) {
876 *output = getOutputForDevice(device, session, *stream, config, flags);
877 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800878 if (*output == AUDIO_IO_HANDLE_NONE) {
879 return INVALID_OPERATION;
880 }
Paul McLeanaa981192015-03-21 09:55:15 -0700881
Eric Laurent8fc147b2018-07-22 19:13:55 -0700882 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700883 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
884 : AUDIO_PORT_HANDLE_NONE;
885
Eric Laurent8fc147b2018-07-22 19:13:55 -0700886exit:
887 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
888 .format = config->format,
889 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700890 *portId = AudioPort::getNextUniqueId();
891
Eric Laurent8fc147b2018-07-22 19:13:55 -0700892 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700893 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
894 requestedDeviceId, *stream,
895 getStrategyForAttr(&attributes),
896 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700898 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700899
900 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
901 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700902
Eric Laurente83b55d2014-11-14 10:06:21 -0800903 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700904}
905
906audio_io_handle_t AudioPolicyManager::getOutputForDevice(
907 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800908 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700909 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800910 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200911 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912{
Andy Hungc88b0642018-04-27 15:42:35 -0700913 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700914 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700915
Eric Laurente552edb2014-03-10 17:42:56 -0700916 // open a direct output if required by specified parameters
917 //force direct flag if offload flag is set: offloading implies a direct output stream
918 // and all common behaviors are driven by checking only the direct flag
919 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200920 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
921 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700922 }
Nadav Bar766fb022018-01-07 12:18:03 +0200923 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
924 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700925 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800926 // only allow deep buffering for music stream type
927 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700929 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200930 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700931 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
932 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200933 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800934 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700935 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200936 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700937 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800938 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200939 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700940 AUDIO_OUTPUT_FLAG_DIRECT);
941 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700942 }
Eric Laurente552edb2014-03-10 17:42:56 -0700943
Nadav Bar766fb022018-01-07 12:18:03 +0200944
Eric Laurentb732cf52014-09-24 19:08:21 -0700945 sp<IOProfile> profile;
946
947 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700948 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200949 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800950 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
951 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700952 goto non_direct_output;
953 }
954
Andy Hung2ddee192015-12-18 17:34:44 -0800955 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
956 // This prevents creating an offloaded track and tearing it down immediately after start
957 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700958 // FIXME: We should check the audio session here but we do not have it in this context.
959 // This may prevent offloading in rare situations where effects are left active by apps
960 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700961
Nadav Bar766fb022018-01-07 12:18:03 +0200962 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800963 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700964 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800965 config->sample_rate,
966 config->format,
967 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200968 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700969 }
970
Eric Laurent1c333e22014-05-20 10:48:17 -0700971 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700972 // exclusive outputs for MMAP and Offload are enforced by different session ids.
973 for (size_t i = 0; i < mOutputs.size(); i++) {
974 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
975 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
976 // reuse direct output if currently open by the same client
977 // and configured with same parameters
978 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700979 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700980 (config->channel_mask == desc->mChannelMask) &&
981 (session == desc->mDirectClientSession)) {
982 desc->mDirectOpenCount++;
983 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
984 mOutputs.keyAt(i), session);
985 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700986 }
987 }
988 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800989
990 if (!profile->canOpenNewIo()) {
991 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700992 }
Eric Laurent861a6282015-05-18 15:40:16 -0700993
Eric Laurent3974e3b2017-12-07 17:58:43 -0800994 sp<SwAudioOutputDescriptor> outputDesc =
995 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800996
Mikhail Naganov708e0382018-05-30 09:53:04 -0700997 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800998 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
999 : String8("");
1000
Dean Wheatley3023b382018-08-09 07:42:40 +10001001 // MSD patch may be using the only output stream that can service this request. Release
1002 // MSD patch to prioritize this request over any active output on MSD.
1003 AudioPatchCollection msdPatches = getMsdPatches();
1004 for (size_t i = 0; i < msdPatches.size(); i++) {
1005 const auto& patch = msdPatches[i];
1006 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1007 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1008 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1009 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1010 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1011 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1012 releaseAudioPatch(patch->mHandle, mUidCached);
1013 break;
1014 }
1015 }
1016 }
1017
Nadav Bar766fb022018-01-07 12:18:03 +02001018 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001019
1020 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001021 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001022 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001023 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001024 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1025 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1026 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1027 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1028 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001029 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001030 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001031 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001032 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001033 if (audio_is_linear_pcm(config->format) &&
1034 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001035 goto non_direct_output;
1036 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001037 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001038 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001039 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001040 outputDesc->mDirectClientSession = session;
1041
Eric Laurente552edb2014-03-10 17:42:56 -07001042 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001044 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001045 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001046 return output;
1047 }
1048
Eric Laurentb732cf52014-09-24 19:08:21 -07001049non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001050
1051 // A request for HW A/V sync cannot fallback to a mixed output because time
1052 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001053 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001054 return AUDIO_IO_HANDLE_NONE;
1055 }
1056
Eric Laurente552edb2014-03-10 17:42:56 -07001057 // ignoring channel mask due to downmix capability in mixer
1058
1059 // open a non direct output
1060
1061 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001062 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001063 // get which output is suitable for the specified stream. The actual
1064 // routing change will happen when startOutput() will be called
1065 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1066
Eric Laurent8838a382014-09-08 16:44:28 -07001067 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001068 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1069 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001070 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001071 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001072 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001073 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001074
Eric Laurente552edb2014-03-10 17:42:56 -07001075 return output;
1076}
1077
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001078sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001079 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001080 if (msdModule != 0) {
1081 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1082 msdModule->getHandle());
1083 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1084 }
1085 return 0;
1086}
1087
1088audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001090 if (msdModule != 0) {
1091 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1092 }
1093 return AUDIO_DEVICE_NONE;
1094}
1095
1096const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1097 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001098 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1099 if (msdModule != 0) {
1100 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1101 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1102 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1103 const struct audio_port_config *source = &patch->mPatch.sources[j];
1104 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1105 source->ext.device.hw_module == msdModule->getHandle()) {
1106 msdPatches.addAudioPatch(patch->mHandle, patch);
1107 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001108 }
1109 }
1110 }
1111 return msdPatches;
1112}
1113
1114status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1115 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1116{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001117 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001118 if (msdModule == nullptr) {
1119 ALOGE("%s() unable to get MSD module", __func__);
1120 return NO_INIT;
1121 }
1122 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1123 if (deviceModule == nullptr) {
1124 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1125 return NO_INIT;
1126 }
1127 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1128 if (inputProfiles.isEmpty()) {
1129 ALOGE("%s() no input profiles for MSD module", __func__);
1130 return NO_INIT;
1131 }
1132 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1133 if (outputProfiles.isEmpty()) {
1134 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1135 return NO_INIT;
1136 }
1137 AudioProfileVector msdProfiles;
1138 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1139 for (const auto &inProfile : inputProfiles) {
1140 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1141 msdProfiles.appendVector(inProfile->getAudioProfiles());
1142 }
1143 }
1144 AudioProfileVector deviceProfiles;
1145 for (const auto &outProfile : outputProfiles) {
1146 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1147 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1148 }
1149 }
1150 struct audio_config_base bestSinkConfig;
1151 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1152 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1153 &bestSinkConfig);
1154 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001155 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1156 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001157 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001158 }
1159 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1160 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1161 sinkConfig->format = bestSinkConfig.format;
1162 // For encoded streams force direct flag to prevent downstream mixing.
1163 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1164 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1165 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1166 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1167 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1168 sourceConfig->format = bestSinkConfig.format;
1169 // Copy input stream directly without any processing (e.g. resampling).
1170 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1171 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1172 if (hwAvSync) {
1173 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1174 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1175 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1176 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1177 }
1178 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1179 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1180 sinkConfig->config_mask |= config_mask;
1181 sourceConfig->config_mask |= config_mask;
1182 return NO_ERROR;
1183}
1184
1185PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1186{
1187 PatchBuilder patchBuilder;
1188 patchBuilder.addSource(getMsdAudioInDevice()).
1189 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1190 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1191 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1192 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1193 // For now, we just forcefully try with HwAvSync first.
1194 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1195 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1196 getBestMsdAudioProfileFor(
1197 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1198 if (res == NO_ERROR) {
1199 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1200 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1201 }
1202 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1203 " supporting PCM format conversion.", __func__);
1204 return patchBuilder;
1205}
1206
1207status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1208 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1209 if (outputDevice == AUDIO_DEVICE_NONE) {
1210 // Use media strategy for unspecified output device. This should only
1211 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1212 // therefore invalidate explicit routing requests.
1213 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1214 }
1215 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1216 const struct audio_patch* patch = patchBuilder.patch();
1217 const AudioPatchCollection msdPatches = getMsdPatches();
1218 if (!msdPatches.isEmpty()) {
1219 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1220 "The current MSD prototype only supports one output patch");
1221 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1222 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1223 return NO_ERROR;
1224 }
1225 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1226 }
1227 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1228 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1229 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1230 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1231 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1232 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1233 return status;
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001237 audio_output_flags_t flags,
1238 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 // select one output among several that provide a path to a particular device or set of
1241 // devices (the list was previously build by getOutputsForDevice()).
1242 // The priority is as follows:
1243 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001244 // 2: the output with the bit depth the closest to the requested one
1245 // 3: the primary output
1246 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001247
1248 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001249 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
1251 if (outputs.size() == 1) {
1252 return outputs[0];
1253 }
1254
1255 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001256 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1257 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1258 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001259 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1260 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001261
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001262 for (audio_io_handle_t output : outputs) {
1263 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001265 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1266 continue;
1267 }
Eric Laurent8838a382014-09-08 16:44:28 -07001268 // if a valid format is specified, skip output if not compatible
1269 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001270 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001271 continue;
1272 }
Eric Laurente6930022016-02-11 10:20:40 -08001273 if (AudioPort::isBetterFormatMatch(
1274 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001275 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001276 bestFormat = outputDesc->mFormat;
1277 }
Eric Laurent8838a382014-09-08 16:44:28 -07001278 }
1279
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001280 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001281 if (commonFlags >= maxCommonFlags) {
1282 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001283 if (format != AUDIO_FORMAT_INVALID
1284 && AudioPort::isBetterFormatMatch(
1285 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001286 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001287 bestFormatForFlags = outputDesc->mFormat;
1288 }
1289 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001290 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001291 maxCommonFlags = commonFlags;
1292 bestFormatForFlags = outputDesc->mFormat;
1293 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001294 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001295 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001296 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001297 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001298 }
1299 }
1300 }
1301
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001302 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001303 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001305 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001306 return outputForFormat;
1307 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001308 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001309 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001310 }
1311
1312 return outputs[0];
1313}
1314
Eric Laurent8fc147b2018-07-22 19:13:55 -07001315status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001316{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001317 ALOGV("%s portId %d", __FUNCTION__, portId);
1318
1319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1320 if (outputDesc == 0) {
1321 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001322 return BAD_VALUE;
1323 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001324 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001325
Eric Laurent8fc147b2018-07-22 19:13:55 -07001326 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001327 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001328
Eric Laurent733ce942017-12-07 12:18:25 -08001329 status_t status = outputDesc->start();
1330 if (status != NO_ERROR) {
1331 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001332 }
1333
Eric Laurent97ac8712018-07-27 18:59:02 -07001334 uint32_t delayMs;
1335 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001336
1337 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001338 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001339 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001341 if (delayMs != 0) {
1342 usleep(delayMs * 1000);
1343 }
1344
1345 return status;
1346}
1347
Eric Laurent97ac8712018-07-27 18:59:02 -07001348status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1349 const sp<TrackClientDescriptor>& client,
1350 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001351{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001352 // cannot start playback of STREAM_TTS if any other output is being used
1353 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001354
1355 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001356 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001357 if (stream == AUDIO_STREAM_TTS) {
1358 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001359 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001360 return INVALID_OPERATION;
1361 } else {
1362 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1363 }
1364 } else {
1365 // some playback other than beacon starts
1366 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1367 }
1368
Eric Laurent77305a62016-07-25 16:39:22 -07001369 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001370 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001371 bool force = !outputDesc->isActive() &&
1372 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001373
Eric Laurent97ac8712018-07-27 18:59:02 -07001374 audio_devices_t device = AUDIO_DEVICE_NONE;
1375 AudioMix *policyMix = NULL;
1376 const char *address = NULL;
1377 if (outputDesc->mPolicyMix != NULL) {
1378 policyMix = outputDesc->mPolicyMix;
1379 address = policyMix->mDeviceAddress.string();
1380 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1381 device = policyMix->mDeviceType;
1382 } else {
1383 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1384 }
1385 }
1386
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001387 // requiresMuteCheck is false when we can bypass mute strategy.
1388 // It covers a common case when there is no materially active audio
1389 // and muting would result in unnecessary delay and dropped audio.
1390 const uint32_t outputLatencyMs = outputDesc->latency();
1391 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1392
Eric Laurente552edb2014-03-10 17:42:56 -07001393 // increment usage count for this stream on the requested output:
1394 // NOTE that the usage count is the same for duplicated output and hardware output which is
1395 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001396 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001397
1398 if (client->hasPreferredDevice(true)) {
1399 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1400 if (device != outputDesc->device()) {
1401 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1402 }
1403 }
Eric Laurente552edb2014-03-10 17:42:56 -07001404
Eric Laurent36829f92017-04-07 19:04:42 -07001405 if (stream == AUDIO_STREAM_MUSIC) {
1406 selectOutputForMusicEffects();
1407 }
1408
Eric Laurent592dd7b2018-08-05 18:58:48 -07001409 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001410 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001411 if (device == AUDIO_DEVICE_NONE) {
1412 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001413 }
Eric Laurent36829f92017-04-07 19:04:42 -07001414
Eric Laurente552edb2014-03-10 17:42:56 -07001415 routing_strategy strategy = getStrategy(stream);
1416 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001417 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1418 (beaconMuteLatency > 0);
1419 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001420 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001421 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001422 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001423 // An output has a shared device if
1424 // - managed by the same hw module
1425 // - supports the currently selected device
1426 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1427 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1428
Eric Laurent77305a62016-07-25 16:39:22 -07001429 // force a device change if any other output is:
1430 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001431 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001432 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001433 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001434 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001435 // change the device currently selected by the other output.
1436 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001437 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001438 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001439 force = true;
1440 }
1441 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001442 // a notification so that audio focus effect can propagate, or that a mute/unmute
1443 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001444 const uint32_t latencyMs = desc->latency();
1445 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1446
1447 if (shouldWait && isActive && (waitMs < latencyMs)) {
1448 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001449 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001450
1451 // Require mute check if another output is on a shared device
1452 // and currently active to have proper drain and avoid pops.
1453 // Note restoring AudioTracks onto this output needs to invoke
1454 // a volume ramp if there is no mute.
1455 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001456 }
1457 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001458
1459 const uint32_t muteWaitMs =
1460 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001461
Eric Laurente552edb2014-03-10 17:42:56 -07001462 // apply volume rules for current stream and device if necessary
1463 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001464 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001465 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001466 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001467
1468 // update the outputs if starting an output with a stream that can affect notification
1469 // routing
1470 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001471
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001472 // force reevaluating accessibility routing when ringtone or alarm starts
1473 if (strategy == STRATEGY_SONIFICATION) {
1474 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1475 }
Eric Laurentdc462862016-07-19 12:29:53 -07001476
1477 if (waitMs > muteWaitMs) {
1478 *delayMs = waitMs - muteWaitMs;
1479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001480
1481 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1482 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1483 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1484 // change occurs after the MixerThread starts and causes a stream volume
1485 // glitch.
1486 //
1487 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
Eric Laurentdc462862016-07-19 12:29:53 -07001489
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001490 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1491 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1492 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1493 }
1494
Eric Laurent97ac8712018-07-27 18:59:02 -07001495 // Automatically enable the remote submix input when output is started on a re routing mix
1496 // of type MIX_TYPE_RECORDERS
1497 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1498 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1499 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1500 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1501 address,
1502 "remote-submix");
1503 }
1504
Eric Laurente552edb2014-03-10 17:42:56 -07001505 return NO_ERROR;
1506}
1507
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001509{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001510 ALOGV("%s portId %d", __FUNCTION__, portId);
1511
1512 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1513 if (outputDesc == 0) {
1514 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 return BAD_VALUE;
1516 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001517 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001518
Eric Laurent97ac8712018-07-27 18:59:02 -07001519 ALOGV("stopOutput() output %d, stream %d, session %d",
1520 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001521
Eric Laurent97ac8712018-07-27 18:59:02 -07001522 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001523
Eric Laurent733ce942017-12-07 12:18:25 -08001524 if (status == NO_ERROR ) {
1525 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001526 }
1527 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001528}
1529
Eric Laurent97ac8712018-07-27 18:59:02 -07001530status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1531 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001532{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001533 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001534 audio_stream_type_t stream = client->stream();
1535
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001536 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1537
Eric Laurent592dd7b2018-08-05 18:58:48 -07001538 if (outputDesc->streamActiveCount(stream) > 0) {
1539 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001540 // Automatically disable the remote submix input when output is stopped on a
1541 // re routing mix of type MIX_TYPE_RECORDERS
1542 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1543 outputDesc->mPolicyMix != NULL &&
1544 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1545 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1546 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1547 outputDesc->mPolicyMix->mDeviceAddress,
1548 "remote-submix");
1549 }
1550 }
1551 bool forceDeviceUpdate = false;
1552 if (client->hasPreferredDevice(true)) {
1553 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1554 forceDeviceUpdate = true;
1555 }
1556
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001558 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001559
Eric Laurente552edb2014-03-10 17:42:56 -07001560 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001561 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001562 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001563 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001564 // delay the device switch by twice the latency because stopOutput() is executed when
1565 // the track stop() command is received and at that time the audio track buffer can
1566 // still contain data that needs to be drained. The latency only covers the audio HAL
1567 // and kernel buffers. Also the latency does not always include additional delay in the
1568 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001569 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001570
1571 // force restoring the device selection on other active outputs if it differs from the
1572 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001573 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001574 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001575 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001576 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001577 desc->isActive() &&
1578 outputDesc->sharesHwModuleWith(desc) &&
1579 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001580 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1581 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001582
Eric Laurentc75307b2015-03-17 15:29:32 -07001583 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001584 newDevice2,
1585 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001586 delayMs);
1587 // re-apply device specific volume if not done by setOutputDevice()
1588 if (!force) {
1589 applyStreamVolumes(desc, newDevice2, delayMs);
1590 }
Eric Laurente552edb2014-03-10 17:42:56 -07001591 }
1592 }
1593 // update the outputs if stopping one with a stream that can affect notification routing
1594 handleNotificationRoutingForStream(stream);
1595 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001596
1597 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1598 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1599 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1600 }
1601
Eric Laurent36829f92017-04-07 19:04:42 -07001602 if (stream == AUDIO_STREAM_MUSIC) {
1603 selectOutputForMusicEffects();
1604 }
Eric Laurente552edb2014-03-10 17:42:56 -07001605 return NO_ERROR;
1606 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001607 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001608 return INVALID_OPERATION;
1609 }
1610}
1611
Eric Laurent8fc147b2018-07-22 19:13:55 -07001612void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001613{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001614 ALOGV("%s portId %d", __FUNCTION__, portId);
1615
1616 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1617 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001618 // If an output descriptor is closed due to a device routing change,
1619 // then there are race conditions with releaseOutput from tracks
1620 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1621 // destroyed shortly thereafter.
1622 //
1623 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001624 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 return;
1626 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001627
1628 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001629
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1631 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001632 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001633 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001634 return;
1635 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001636 if (--outputDesc->mDirectOpenCount == 0) {
1637 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001638 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001639 }
1640 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001641 // stopOutput() needs to be successfully called before releaseOutput()
1642 // otherwise there may be inaccurate stream reference counts.
1643 // This is checked in outputDesc->removeClient below.
1644 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001645}
1646
Eric Laurentcaf7f482014-11-25 17:50:47 -08001647status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1648 audio_io_handle_t *input,
1649 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001650 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001651 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001652 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001653 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001654 input_type_t *inputType,
1655 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001656{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001657 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001658 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001659 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001660
Eric Laurentad2e7b92017-09-14 20:06:42 -07001661 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001662 // handle legacy remote submix case where the address was not always specified
1663 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001664 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001665 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001666 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001667 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001668 sp<AudioInputDescriptor> inputDesc;
1669 sp<RecordClientDescriptor> clientDesc;
1670 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001671 bool isSoundTrigger;
1672 audio_devices_t device;
1673
1674 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1675 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1676 return INVALID_OPERATION;
1677 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001678
Eric Laurentfe231122017-11-17 17:48:06 -08001679 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1680 inputSource = AUDIO_SOURCE_MIC;
1681 }
1682
Paul McLean466dc8e2015-04-17 13:15:36 -06001683 // Explicit routing?
1684 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001685 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001686 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001687 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001688
Eric Laurentad2e7b92017-09-14 20:06:42 -07001689 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1690 // possible
1691 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1692 *input != AUDIO_IO_HANDLE_NONE) {
1693 ssize_t index = mInputs.indexOfKey(*input);
1694 if (index < 0) {
1695 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1696 status = BAD_VALUE;
1697 goto error;
1698 }
1699 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001700 RecordClientVector clients = inputDesc->getClientsForSession(session);
1701 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001702 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1703 status = BAD_VALUE;
1704 goto error;
1705 }
1706 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1707 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001708 // corresponds to a new client and is only permitted from the same UID.
1709 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001710 if (clients.size() > 1) {
1711 for (const auto& client : clients) {
1712 // The client map is ordered by key values (portId) and portIds are allocated
1713 // incrementaly. So the first client in this list is the one opened by audio flinger
1714 // when the mmap stream is created and should be ignored as it does not correspond
1715 // to an actual client
1716 if (client == *clients.cbegin()) {
1717 continue;
1718 }
1719 if (uid != client->uid() && !client->isSilenced()) {
1720 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1721 uid, client->portId(), client->uid());
1722 status = INVALID_OPERATION;
1723 goto error;
1724 }
Eric Laurent331679c2018-04-16 17:03:16 -07001725 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001726 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001727 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001728 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001729
Eric Laurent8f42ea12018-08-08 09:08:25 -07001730 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001731 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001732 }
1733
1734 *input = AUDIO_IO_HANDLE_NONE;
1735 *inputType = API_INPUT_INVALID;
1736
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 halInputSource = inputSource;
1738
Eric Laurentc447ded2015-01-06 08:47:05 -08001739 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001740 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001741 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1742 if (status != NO_ERROR) {
1743 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001744 }
1745 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1747 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001748 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001749 if (deviceDesc != 0) {
1750 device = deviceDesc->type();
1751 } else {
1752 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1753 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001754 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001755 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001756 status = BAD_VALUE;
1757 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001758 }
Eric Laurentc722f302014-12-10 11:21:49 -08001759 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001760 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001761 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1762 // there is an external policy, but this input is attached to a mix of recorders,
1763 // meaning it receives audio injected into the framework, so the recorder doesn't
1764 // know about it and is therefore considered "legacy"
1765 *inputType = API_INPUT_LEGACY;
1766 } else {
1767 // recording a mix of players defined by an external policy, we're rerouting for
1768 // an external policy
1769 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1770 }
Eric Laurentc722f302014-12-10 11:21:49 -08001771 } else if (audio_is_remote_submix_device(device)) {
1772 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001773 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001774 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1775 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001776 } else {
1777 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001778 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001779
Eric Laurent599c7582015-12-07 18:05:55 -08001780 }
1781
Eric Laurent8f42ea12018-08-08 09:08:25 -07001782 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001783 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001784 policyMix);
1785 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001786 status = INVALID_OPERATION;
1787 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001788 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001789
Eric Laurent8f42ea12018-08-08 09:08:25 -07001790exit:
1791
Mikhail Naganov708e0382018-05-30 09:53:04 -07001792 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001793 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001794 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001795
Eric Laurent8f42ea12018-08-08 09:08:25 -07001796 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1797 mSoundTriggerSessions.indexOfKey(session) > 0;
1798 *portId = AudioPort::getNextUniqueId();
1799
Eric Laurent8fc147b2018-07-22 19:13:55 -07001800 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001801 *attr, *config, requestedDeviceId,
1802 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001803 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001804 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001805
1806 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1807 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001808
Eric Laurent599c7582015-12-07 18:05:55 -08001809 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810
1811error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001812 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001813}
1814
1815
1816audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1817 String8 address,
1818 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001819 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001820 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001821 audio_input_flags_t flags,
1822 AudioMix *policyMix)
1823{
1824 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1825 audio_source_t halInputSource = inputSource;
1826 bool isSoundTrigger = false;
1827
1828 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1829 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1830 if (index >= 0) {
1831 input = mSoundTriggerSessions.valueFor(session);
1832 isSoundTrigger = true;
1833 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1834 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1835 } else {
1836 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001837 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001838 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001839 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001840 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001841 }
1842
Andy Hungf129b032015-04-07 13:45:50 -07001843 // find a compatible input profile (not necessarily identical in parameters)
1844 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001845 // sampling rate and flags may be updated by getInputProfile
1846 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1847 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001848 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001849 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001850 audio_input_flags_t profileFlags = flags;
1851 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001852 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001853 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001854 profileSamplingRate, profileFormat, profileChannelMask,
1855 profileFlags);
1856 if (profile != 0) {
1857 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001858 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1859 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001860 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1861 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1862 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001863 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001864 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1865 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001866 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001867 }
Eric Laurente552edb2014-03-10 17:42:56 -07001868 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001869 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001870 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001871 if (samplingRate == 0) {
1872 samplingRate = profileSamplingRate;
1873 }
Eric Laurente552edb2014-03-10 17:42:56 -07001874
Eric Laurent322b4d22015-04-03 15:57:54 -07001875 if (profile->getModuleHandle() == 0) {
1876 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001877 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001878 }
1879
Eric Laurent3974e3b2017-12-07 17:58:43 -08001880 if (!profile->canOpenNewIo()) {
1881 return AUDIO_IO_HANDLE_NONE;
1882 }
1883
Eric Laurentfe231122017-11-17 17:48:06 -08001884 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001885
Eric Laurentfe231122017-11-17 17:48:06 -08001886 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1887 lConfig.sample_rate = profileSamplingRate;
1888 lConfig.channel_mask = profileChannelMask;
1889 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001890
Eric Laurent53b810e2017-12-10 17:25:10 -08001891 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001892 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001893 // the inputs vector must be of size >= 1, but we don't want to crash here
1894 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1895 }
1896
Eric Laurentfe231122017-11-17 17:48:06 -08001897 status_t status = inputDesc->open(&lConfig, device, address,
1898 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001899
1900 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001901 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001902 (profileSamplingRate != lConfig.sample_rate) ||
1903 !audio_formats_match(profileFormat, lConfig.format) ||
1904 (profileChannelMask != lConfig.channel_mask)) {
1905 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001906 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001907 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001908 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001909 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001910 }
Eric Laurent599c7582015-12-07 18:05:55 -08001911 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001912 }
1913
Eric Laurentc722f302014-12-10 11:21:49 -08001914 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001915
Eric Laurent599c7582015-12-07 18:05:55 -08001916 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001917 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001918
Eric Laurent599c7582015-12-07 18:05:55 -08001919 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001920}
1921
Eric Laurentbb948092017-01-23 18:33:30 -08001922//static
1923bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1924{
1925 return (source == AUDIO_SOURCE_HOTWORD) ||
1926 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1927 (source == AUDIO_SOURCE_FM_TUNER);
1928}
1929
Chris Thornton2b864642017-06-27 21:26:07 -07001930// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1931bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1932 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1933 bool soundTriggerSupportsConcurrentCapture = false;
1934 unsigned int numModules = 0;
1935 struct sound_trigger_module_descriptor* nModules = NULL;
1936
1937 status_t status = SoundTrigger::listModules(nModules, &numModules);
1938 if (status == NO_ERROR && numModules != 0) {
1939 nModules = (struct sound_trigger_module_descriptor*) calloc(
1940 numModules, sizeof(struct sound_trigger_module_descriptor));
1941 if (nModules == NULL) {
1942 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1943 // ram the next time this function is called.
1944 ALOGE("Failed to allocate buffer for module descriptors");
1945 return false;
1946 }
1947
1948 status = SoundTrigger::listModules(nModules, &numModules);
1949 if (status == NO_ERROR) {
1950 soundTriggerSupportsConcurrentCapture = true;
1951 for (size_t i = 0; i < numModules; ++i) {
1952 soundTriggerSupportsConcurrentCapture &=
1953 nModules[i].properties.concurrent_capture;
1954 }
1955 }
1956 free(nModules);
1957 }
1958 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1959 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1960 }
1961 return mSoundTriggerSupportsConcurrentCapture;
1962}
1963
Eric Laurentfb66dd92016-01-28 18:32:03 -08001964
Eric Laurent8fc147b2018-07-22 19:13:55 -07001965status_t AudioPolicyManager::startInput(audio_port_handle_t portId,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001966 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001967 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001968{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001969 *concurrency = API_INPUT_CONCURRENCY_NONE;
1970
1971 ALOGV("%s portId %d", __FUNCTION__, portId);
1972
1973 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1974 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001975 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976 return BAD_VALUE;
1977 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001978 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001979 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001980 if (client->active()) {
1981 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1982 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001983 }
1984
Eric Laurent8f42ea12018-08-08 09:08:25 -07001985 audio_session_t session = client->session();
1986
1987 ALOGV("%s input:%d, session:%d, silenced:%d, concurrency:%d)",
1988 __FUNCTION__, input, session, silenced, *concurrency);
1989
Eric Laurent74708e72017-04-07 17:13:42 -07001990 if (!is_virtual_input_device(inputDesc->mDevice)) {
1991 if (mCallTxPatch != 0 &&
1992 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1993 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001994 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001995 return INVALID_OPERATION;
1996 }
1997
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001998 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001999
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002000 // If a UID is idle and records silence and another not silenced recording starts
2001 // from another UID (idle or active) we stop the current idle UID recording in
2002 // favor of the new one - "There can be only one" TM
2003 if (!silenced) {
2004 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002005 if ((activeDesc->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002006 activeDesc->getId() == inputDesc->getId()) {
2007 continue;
2008 }
2009
Eric Laurent8f42ea12018-08-08 09:08:25 -07002010 RecordClientVector activeClients = activeDesc->clientsList(true /*activeOnly*/);
2011 for (const auto& activeClient : activeClients) {
2012 if (activeClient->isSilenced()) {
2013 closeClient(activeClient->portId());
2014 ALOGV("%s client %d stopping silenced client %d", __FUNCTION__,
2015 portId, activeClient->portId());
2016 activeInputs = mInputs.getActiveInputs();
2017 }
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002018 }
2019 }
2020 }
2021
2022 for (const auto& activeDesc : activeInputs) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002023 if ((client->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
Eric Laurentcb4dae22017-07-01 19:39:32 -07002024 activeDesc->getId() == inputDesc->getId()) {
2025 continue;
2026 }
2027
Eric Laurent74708e72017-04-07 17:13:42 -07002028 audio_source_t activeSource = activeDesc->inputSource(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002029 if (client->source() == AUDIO_SOURCE_HOTWORD) {
Eric Laurent74708e72017-04-07 17:13:42 -07002030 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2031 if (activeDesc->hasPreemptedSession(session)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002032 ALOGW("%s input %d failed for HOTWORD: "
2033 "other input %d already started for HOTWORD", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002034 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002035 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07002036 return INVALID_OPERATION;
2037 }
2038 } else {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002039 ALOGV("%s input %d failed for HOTWORD: other input %d already started",
2040 __FUNCTION__, input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002041 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002042 return INVALID_OPERATION;
2043 }
2044 } else {
2045 if (activeSource != AUDIO_SOURCE_HOTWORD) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002046 ALOGW("%s input %d failed: other input %d already started", __FUNCTION__,
Eric Laurent74708e72017-04-07 17:13:42 -07002047 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002048 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002049 return INVALID_OPERATION;
2050 }
2051 }
2052 }
2053
Chris Thornton2b864642017-06-27 21:26:07 -07002054 // We only need to check if the sound trigger session supports concurrent capture if the
2055 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2056 // that's running.
2057 const bool allowConcurrentWithSoundTrigger =
2058 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2059
Eric Laurent74708e72017-04-07 17:13:42 -07002060 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002061 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002062 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2063 continue;
2064 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065 RecordClientVector activeHotwordClients =
2066 activeDesc->clientsList(true, AUDIO_SOURCE_HOTWORD);
2067 if (activeHotwordClients.size() > 0) {
Eric Laurent74708e72017-04-07 17:13:42 -07002068 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002069
2070 for (const auto& activeClient : activeHotwordClients) {
2071 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
2072 sessions.add(activeClient->session());
2073 closeClient(activeClient->portId());
2074 ALOGV("%s input %d for HOTWORD preempting HOTWORD input %d", __FUNCTION__,
2075 input, activeDesc->mIoHandle);
2076 }
2077
Eric Laurent74708e72017-04-07 17:13:42 -07002078 inputDesc->setPreemptedSessions(sessions);
Eric Laurent74708e72017-04-07 17:13:42 -07002079 }
2080 }
2081 }
Eric Laurente552edb2014-03-10 17:42:56 -07002082
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002083 // Make sure we start with the correct silence state
Eric Laurent8f42ea12018-08-08 09:08:25 -07002084 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002085
Eric Laurent313d1e72016-01-29 09:56:57 -08002086 // increment activity count before calling getNewInputDevice() below as only active sessions
2087 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002088 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002089
Eric Laurent8f42ea12018-08-08 09:08:25 -07002090 // indicate active capture to sound trigger service if starting capture from a mic on
2091 // primary HW module
2092 audio_devices_t device = getNewInputDevice(inputDesc);
2093 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002094
Eric Laurent8f42ea12018-08-08 09:08:25 -07002095 status_t status = inputDesc->start();
2096 if (status != NO_ERROR) {
2097 inputDesc->setClientActive(client, false);
2098 return status;
2099 }
2100
2101 if (inputDesc->activeCount() == 1) {
2102 // if input maps to a dynamic policy with an activity listener, notify of state change
2103 if ((inputDesc->mPolicyMix != NULL)
2104 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2105 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2106 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002107 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002108
Eric Laurent8f42ea12018-08-08 09:08:25 -07002109 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2110 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2111 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2112 SoundTrigger::setCaptureState(true);
2113 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002114
Eric Laurent8f42ea12018-08-08 09:08:25 -07002115 // automatically enable the remote submix output when input is started if not
2116 // used by a policy mix of type MIX_TYPE_RECORDERS
2117 // For remote submix (a virtual device), we open only one input per capture request.
2118 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2119 String8 address = String8("");
2120 if (inputDesc->mPolicyMix == NULL) {
2121 address = String8("0");
2122 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2123 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002124 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002125 if (address != "") {
2126 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2127 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2128 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002129 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002130 }
Eric Laurente552edb2014-03-10 17:42:56 -07002131 }
2132
Eric Laurent8f42ea12018-08-08 09:08:25 -07002133 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002134
Eric Laurente552edb2014-03-10 17:42:56 -07002135 return NO_ERROR;
2136}
2137
Eric Laurent8fc147b2018-07-22 19:13:55 -07002138status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002139{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002140 ALOGV("%s portId %d", __FUNCTION__, portId);
2141
2142 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2143 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002144 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002145 return BAD_VALUE;
2146 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002147 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002148 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002149 if (!client->active()) {
2150 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002151 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002152 }
2153
Eric Laurent8f42ea12018-08-08 09:08:25 -07002154 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002155
Eric Laurent8f42ea12018-08-08 09:08:25 -07002156 inputDesc->stop();
2157 if (inputDesc->isActive()) {
2158 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2159 } else {
2160 // if input maps to a dynamic policy with an activity listener, notify of state change
2161 if ((inputDesc->mPolicyMix != NULL)
2162 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2163 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2164 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002165 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166
2167 // automatically disable the remote submix output when input is stopped if not
2168 // used by a policy mix of type MIX_TYPE_RECORDERS
2169 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2170 String8 address = String8("");
2171 if (inputDesc->mPolicyMix == NULL) {
2172 address = String8("0");
2173 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2174 address = inputDesc->mPolicyMix->mDeviceAddress;
2175 }
2176 if (address != "") {
2177 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2178 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2179 address, "remote-submix");
2180 }
2181 }
2182
2183 audio_devices_t device = inputDesc->mDevice;
2184 resetInputDevice(input);
2185
2186 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2187 // primary HW module
2188 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2189 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2190 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2191 SoundTrigger::setCaptureState(false);
2192 }
2193 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002194 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002195 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002196}
2197
Eric Laurent8fc147b2018-07-22 19:13:55 -07002198void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002199{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200 ALOGV("%s portId %d", __FUNCTION__, portId);
2201
2202 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2203 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002204 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002205 return;
2206 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002207 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002208 audio_io_handle_t input = inputDesc->mIoHandle;
2209
Eric Laurent8f42ea12018-08-08 09:08:25 -07002210 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002211
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002213
Andy Hung39efb7a2018-09-26 15:39:28 -07002214 if (inputDesc->getClientCount() > 0) {
2215 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002216 return;
2217 }
2218
Eric Laurent05b90f82014-08-27 15:32:29 -07002219 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002220 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002221 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002222}
2223
Eric Laurent8f42ea12018-08-08 09:08:25 -07002224void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002225{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002226 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002227
2228 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002229 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230 }
2231}
2232
Eric Laurent8f42ea12018-08-08 09:08:25 -07002233void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2234{
2235 stopInput(portId);
2236 releaseInput(portId);
2237}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002238
Eric Laurentd4692962014-05-05 18:13:44 -07002239void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002240 bool patchRemoved = false;
2241
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002242 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002243 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002244 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002245 if (patch_index >= 0) {
2246 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002247 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002248 mAudioPatches.removeItemsAt(patch_index);
2249 patchRemoved = true;
2250 }
Eric Laurentfe231122017-11-17 17:48:06 -08002251 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002252 }
2253 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002254 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002255 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002256
2257 if (patchRemoved) {
2258 mpClientInterface->onAudioPatchListUpdate();
2259 }
Eric Laurentd4692962014-05-05 18:13:44 -07002260}
2261
Eric Laurente0720872014-03-11 09:30:41 -07002262void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002263 int indexMin,
2264 int indexMax)
2265{
2266 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002267 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002268
2269 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002270 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2271 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002272 continue;
2273 }
2274 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002275 }
Eric Laurente552edb2014-03-10 17:42:56 -07002276}
2277
Eric Laurente0720872014-03-11 09:30:41 -07002278status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002279 int index,
2280 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002281{
2282
Nadav Bar7c605f62017-12-25 00:01:52 +02002283 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2284 // app that has MODIFY_PHONE_STATE permission.
2285 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2286 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002287 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002288 return BAD_VALUE;
2289 }
2290 if (!audio_is_output_device(device)) {
2291 return BAD_VALUE;
2292 }
2293
2294 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002295 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002296
Eric Laurent1fd372e2016-04-06 14:23:53 -07002297 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002298 stream, device, index);
2299
Eric Laurent28d09f02016-03-08 10:43:05 -08002300 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002301 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2302 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002303 continue;
2304 }
2305 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2306 }
Eric Laurente552edb2014-03-10 17:42:56 -07002307
Eric Laurent1fd372e2016-04-06 14:23:53 -07002308 // update volume on all outputs and streams matching the following:
2309 // - The requested stream (or a stream matching for volume control) is active on the output
2310 // - The device (or devices) selected by the strategy corresponding to this stream includes
2311 // the requested device
2312 // - For non default requested device, currently selected device on the output is either the
2313 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002314 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2315 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002316 status_t status = NO_ERROR;
2317 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2319 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002320 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002321 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002322 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002323 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002324 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002325 continue;
2326 }
Eric Laurent794fde22016-03-11 09:50:45 -08002327 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002328 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2329 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002330 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2331 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002332 continue;
2333 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002334 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002335 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002336 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002337 applyVolume = (curDevice & curStreamDevice) != 0;
2338 } else {
2339 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002340 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002341 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002342 // rescale index before applying to curStream as ranges may be different for
2343 // stream and curStream
2344 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002345 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002346 //FIXME: workaround for truncated touch sounds
2347 // delayed volume change for system stream to be removed when the problem is
2348 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002349 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002350 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002351 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002352 if (volStatus != NO_ERROR) {
2353 status = volStatus;
2354 }
2355 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002356 }
Eric Laurente552edb2014-03-10 17:42:56 -07002357 }
2358 return status;
2359}
2360
Eric Laurente0720872014-03-11 09:30:41 -07002361status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002362 int *index,
2363 audio_devices_t device)
2364{
2365 if (index == NULL) {
2366 return BAD_VALUE;
2367 }
2368 if (!audio_is_output_device(device)) {
2369 return BAD_VALUE;
2370 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002371 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002372 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002373 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002374 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2375 }
François Gaffiedfd74092015-03-19 12:10:59 +01002376 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002377
François Gaffied1ab2bd2015-12-02 18:20:06 +01002378 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002379 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2380 return NO_ERROR;
2381}
2382
Eric Laurent36829f92017-04-07 19:04:42 -07002383audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002384{
2385 // select one output among several suitable for global effects.
2386 // The priority is as follows:
2387 // 1: An offloaded output. If the effect ends up not being offloadable,
2388 // AudioFlinger will invalidate the track and the offloaded output
2389 // will be closed causing the effect to be moved to a PCM output.
2390 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002391 // 3: The primary output
2392 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Eric Laurent3b73df72014-03-11 09:06:29 -07002394 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002395 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002396 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent36829f92017-04-07 19:04:42 -07002398 if (outputs.size() == 0) {
2399 return AUDIO_IO_HANDLE_NONE;
2400 }
Eric Laurente552edb2014-03-10 17:42:56 -07002401
Eric Laurent36829f92017-04-07 19:04:42 -07002402 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2403 bool activeOnly = true;
2404
2405 while (output == AUDIO_IO_HANDLE_NONE) {
2406 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2407 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2408 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2409
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002410 for (audio_io_handle_t output : outputs) {
2411 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002412 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2413 continue;
2414 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002415 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2416 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002417 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002418 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002419 }
2420 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002421 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002422 }
2423 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002424 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002425 }
2426 }
2427 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2428 output = outputOffloaded;
2429 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2430 output = outputDeepBuffer;
2431 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2432 output = outputPrimary;
2433 } else {
2434 output = outputs[0];
2435 }
2436 activeOnly = false;
2437 }
2438
2439 if (output != mMusicEffectOutput) {
2440 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2441 mMusicEffectOutput = output;
2442 }
2443
2444 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002445 return output;
2446}
2447
Eric Laurent36829f92017-04-07 19:04:42 -07002448audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2449{
2450 return selectOutputForMusicEffects();
2451}
2452
Eric Laurente0720872014-03-11 09:30:41 -07002453status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002454 audio_io_handle_t io,
2455 uint32_t strategy,
2456 int session,
2457 int id)
2458{
2459 ssize_t index = mOutputs.indexOfKey(io);
2460 if (index < 0) {
2461 index = mInputs.indexOfKey(io);
2462 if (index < 0) {
2463 ALOGW("registerEffect() unknown io %d", io);
2464 return INVALID_OPERATION;
2465 }
2466 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002467 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002468}
2469
Eric Laurentc75307b2015-03-17 15:29:32 -07002470bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2471{
Eric Laurent28d09f02016-03-08 10:43:05 -08002472 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002473 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2474 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002475 continue;
2476 }
2477 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2478 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002479 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002480}
2481
2482bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2483{
2484 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2485}
2486
Eric Laurente0720872014-03-11 09:30:41 -07002487bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002488{
2489 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002490 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002491 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002492 return true;
2493 }
2494 }
2495 return false;
2496}
2497
Eric Laurent275e8e92014-11-30 15:14:47 -08002498// Register a list of custom mixes with their attributes and format.
2499// When a mix is registered, corresponding input and output profiles are
2500// added to the remote submix hw module. The profile contains only the
2501// parameters (sampling rate, format...) specified by the mix.
2502// The corresponding input remote submix device is also connected.
2503//
2504// When a remote submix device is connected, the address is checked to select the
2505// appropriate profile and the corresponding input or output stream is opened.
2506//
2507// When capture starts, getInputForAttr() will:
2508// - 1 look for a mix matching the address passed in attribtutes tags if any
2509// - 2 if none found, getDeviceForInputSource() will:
2510// - 2.1 look for a mix matching the attributes source
2511// - 2.2 if none found, default to device selection by policy rules
2512// At this time, the corresponding output remote submix device is also connected
2513// and active playback use cases can be transferred to this mix if needed when reconnecting
2514// after AudioTracks are invalidated
2515//
2516// When playback starts, getOutputForAttr() will:
2517// - 1 look for a mix matching the address passed in attribtutes tags if any
2518// - 2 if none found, look for a mix matching the attributes usage
2519// - 3 if none found, default to device and output selection by policy rules.
2520
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002521status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002522{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2524 status_t res = NO_ERROR;
2525
2526 sp<HwModule> rSubmixModule;
2527 // examine each mix's route type
2528 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002529 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002531 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002532 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002533 break;
2534 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002535 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002537 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002538 rSubmixModule = mHwModules.getModuleFromName(
2539 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2540 if (rSubmixModule == 0) {
2541 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2542 i);
2543 res = INVALID_OPERATION;
2544 break;
2545 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002547
Eric Laurent97ac8712018-07-27 18:59:02 -07002548 String8 address = mix.mDeviceAddress;
2549 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2550 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2551 } else {
2552 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2553 }
François Gaffie036e1e92015-03-19 10:16:24 +01002554
Eric Laurent97ac8712018-07-27 18:59:02 -07002555 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002556 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 res = INVALID_OPERATION;
2558 break;
2559 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002560 audio_config_t outputConfig = mix.mFormat;
2561 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002562 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2563 // stereo and let audio flinger do the channel conversion if needed.
2564 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2565 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2566 rSubmixModule->addOutputProfile(address, &outputConfig,
2567 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2568 rSubmixModule->addInputProfile(address, &inputConfig,
2569 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002570
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002572 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2573 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2574 address.string(), "remote-submix");
2575 } else {
2576 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2578 address.string(), "remote-submix");
2579 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002580 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2581 String8 address = mix.mDeviceAddress;
2582 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002583 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2584 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002586 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2589 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2590 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2591 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2592 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002593 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2594 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002595 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002596 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002597 } else {
2598 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002599 }
2600 break;
2601 }
2602 }
2603
2604 if (res != NO_ERROR) {
2605 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002606 i, device, address.string());
2607 res = INVALID_OPERATION;
2608 break;
2609 } else if (!foundOutput) {
2610 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2611 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002612 res = INVALID_OPERATION;
2613 break;
2614 }
Eric Laurentc722f302014-12-10 11:21:49 -08002615 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002616 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002617 if (res != NO_ERROR) {
2618 unregisterPolicyMixes(mixes);
2619 }
2620 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002621}
2622
2623status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2624{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002625 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 status_t res = NO_ERROR;
2627 sp<HwModule> rSubmixModule;
2628 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002629 for (const auto& mix : mixes) {
2630 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002631
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002632 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002633 rSubmixModule = mHwModules.getModuleFromName(
2634 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2635 if (rSubmixModule == 0) {
2636 res = INVALID_OPERATION;
2637 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 }
2639 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002640
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002641 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002642
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002643 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2644 res = INVALID_OPERATION;
2645 continue;
2646 }
2647
2648 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2649 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2650 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2651 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2652 address.string(), "remote-submix");
2653 }
2654 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2655 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2656 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2657 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2658 address.string(), "remote-submix");
2659 }
2660 rSubmixModule->removeOutputProfile(address);
2661 rSubmixModule->removeInputProfile(address);
2662
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002663 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2664 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002665 res = INVALID_OPERATION;
2666 continue;
2667 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002668 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002669 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002670 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002671}
2672
Andy Hungc29d82b2018-10-05 12:23:17 -07002673void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002674{
Andy Hungc29d82b2018-10-05 12:23:17 -07002675 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2676 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002677 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002678 std::string stateLiteral;
2679 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002680 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002681 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2682 "communications", "media", "record", "dock", "system",
2683 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2684 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2685 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002686 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002687 forceUses[i], mEngine->getForceUse(i));
2688 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002689 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2690 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2691 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2692 mAvailableOutputDevices.dump(dst, String8("Available output"));
2693 mAvailableInputDevices.dump(dst, String8("Available input"));
2694 mHwModulesAll.dump(dst);
2695 mOutputs.dump(dst);
2696 mInputs.dump(dst);
2697 mVolumeCurves->dump(dst);
2698 mEffects.dump(dst);
2699 mAudioPatches.dump(dst);
2700 mPolicyMixes.dump(dst);
2701 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002702 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002703 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002704 size_t i = 0;
2705 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002706 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002707 std::string sfmt;
2708 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002709 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002710 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002711 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002712 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002713}
2714
2715status_t AudioPolicyManager::dump(int fd)
2716{
2717 String8 result;
2718 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002719 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002720 return NO_ERROR;
2721}
2722
2723// This function checks for the parameters which can be offloaded.
2724// This can be enhanced depending on the capability of the DSP and policy
2725// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002726bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002727{
2728 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002729 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002730 offloadInfo.sample_rate, offloadInfo.channel_mask,
2731 offloadInfo.format,
2732 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2733 offloadInfo.has_video);
2734
Andy Hung2ddee192015-12-18 17:34:44 -08002735 if (mMasterMono) {
2736 return false; // no offloading if mono is set.
2737 }
2738
Eric Laurente552edb2014-03-10 17:42:56 -07002739 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002740 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2741 ALOGV("offload disabled by audio.offload.disable");
2742 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002743 }
2744
2745 // Check if stream type is music, then only allow offload as of now.
2746 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2747 {
2748 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2749 return false;
2750 }
2751
2752 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002753 const bool allowOffloadWithVideo =
2754 property_get_bool("audio.offload.video", false /* default_value */);
2755 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002756 ALOGV("isOffloadSupported: has_video == true, returning false");
2757 return false;
2758 }
2759
2760 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002761 const int min_duration_secs = property_get_int32(
2762 "audio.offload.min.duration.secs", -1 /* default_value */);
2763 if (min_duration_secs >= 0) {
2764 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2765 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2766 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002767 return false;
2768 }
2769 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2770 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2771 return false;
2772 }
2773
2774 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2775 // creating an offloaded track and tearing it down immediately after start when audioflinger
2776 // detects there is an active non offloadable effect.
2777 // FIXME: We should check the audio session here but we do not have it in this context.
2778 // This may prevent offloading in rare situations where effects are left active by apps
2779 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002780 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002781 return false;
2782 }
2783
2784 // See if there is a profile to support this.
2785 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002786 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002787 offloadInfo.sample_rate,
2788 offloadInfo.format,
2789 offloadInfo.channel_mask,
2790 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002791 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2792 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002793}
2794
Eric Laurent6a94d692014-05-20 11:18:06 -07002795status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2796 audio_port_type_t type,
2797 unsigned int *num_ports,
2798 struct audio_port *ports,
2799 unsigned int *generation)
2800{
2801 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2802 generation == NULL) {
2803 return BAD_VALUE;
2804 }
2805 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2806 if (ports == NULL) {
2807 *num_ports = 0;
2808 }
2809
2810 size_t portsWritten = 0;
2811 size_t portsMax = *num_ports;
2812 *num_ports = 0;
2813 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002814 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2815 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002817 for (const auto& dev : mAvailableOutputDevices) {
2818 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002819 continue;
2820 }
2821 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002822 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002823 }
2824 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002825 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002826 }
2827 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002828 for (const auto& dev : mAvailableInputDevices) {
2829 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002830 continue;
2831 }
2832 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002833 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002834 }
2835 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002837 }
2838 }
2839 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2840 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2841 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2842 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2843 }
2844 *num_ports += mInputs.size();
2845 }
2846 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002847 size_t numOutputs = 0;
2848 for (size_t i = 0; i < mOutputs.size(); i++) {
2849 if (!mOutputs[i]->isDuplicated()) {
2850 numOutputs++;
2851 if (portsWritten < portsMax) {
2852 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2853 }
2854 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002855 }
Eric Laurent84c70242014-06-23 08:46:27 -07002856 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002857 }
2858 }
2859 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002860 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002861 return NO_ERROR;
2862}
2863
Eric Laurent99fcae42018-05-17 16:59:18 -07002864status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002865{
Eric Laurent99fcae42018-05-17 16:59:18 -07002866 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2867 return BAD_VALUE;
2868 }
2869 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2870 if (dev != 0) {
2871 dev->toAudioPort(port);
2872 return NO_ERROR;
2873 }
2874 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2875 if (dev != 0) {
2876 dev->toAudioPort(port);
2877 return NO_ERROR;
2878 }
2879 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2880 if (out != 0) {
2881 out->toAudioPort(port);
2882 return NO_ERROR;
2883 }
2884 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2885 if (in != 0) {
2886 in->toAudioPort(port);
2887 return NO_ERROR;
2888 }
2889 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002890}
2891
Eric Laurent6a94d692014-05-20 11:18:06 -07002892status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2893 audio_patch_handle_t *handle,
2894 uid_t uid)
2895{
2896 ALOGV("createAudioPatch()");
2897
2898 if (handle == NULL || patch == NULL) {
2899 return BAD_VALUE;
2900 }
2901 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2902
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002903 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002904 return BAD_VALUE;
2905 }
2906 // only one source per audio patch supported for now
2907 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 return INVALID_OPERATION;
2909 }
Eric Laurent874c42872014-08-08 15:13:39 -07002910
2911 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002912 return INVALID_OPERATION;
2913 }
Eric Laurent874c42872014-08-08 15:13:39 -07002914 for (size_t i = 0; i < patch->num_sinks; i++) {
2915 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2916 return INVALID_OPERATION;
2917 }
2918 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002919
2920 sp<AudioPatch> patchDesc;
2921 ssize_t index = mAudioPatches.indexOfKey(*handle);
2922
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2924 patch->sources[0].role,
2925 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002926#if LOG_NDEBUG == 0
2927 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002928 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002929 patch->sinks[i].role,
2930 patch->sinks[i].type);
2931 }
2932#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002933
2934 if (index >= 0) {
2935 patchDesc = mAudioPatches.valueAt(index);
2936 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2937 mUidCached, patchDesc->mUid, uid);
2938 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2939 return INVALID_OPERATION;
2940 }
2941 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002942 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002943 }
2944
2945 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002946 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002947 if (outputDesc == NULL) {
2948 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2949 return BAD_VALUE;
2950 }
Eric Laurent84c70242014-06-23 08:46:27 -07002951 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2952 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002953 if (patchDesc != 0) {
2954 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2955 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2956 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2957 return BAD_VALUE;
2958 }
2959 }
Eric Laurent874c42872014-08-08 15:13:39 -07002960 DeviceVector devices;
2961 for (size_t i = 0; i < patch->num_sinks; i++) {
2962 // Only support mix to devices connection
2963 // TODO add support for mix to mix connection
2964 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2965 ALOGV("createAudioPatch() source mix but sink is not a device");
2966 return INVALID_OPERATION;
2967 }
2968 sp<DeviceDescriptor> devDesc =
2969 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2970 if (devDesc == 0) {
2971 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2972 return BAD_VALUE;
2973 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002974
François Gaffie53615e22015-03-19 09:24:12 +01002975 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002976 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002977 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002978 NULL, // updatedSamplingRate
2979 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002980 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002981 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002982 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002983 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002984 ALOGV("createAudioPatch() profile not supported for device %08x",
2985 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002986 return INVALID_OPERATION;
2987 }
2988 devices.add(devDesc);
2989 }
2990 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 return INVALID_OPERATION;
2992 }
Eric Laurent874c42872014-08-08 15:13:39 -07002993
Eric Laurent6a94d692014-05-20 11:18:06 -07002994 // TODO: reconfigure output format and channels here
2995 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002996 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002997 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002998 index = mAudioPatches.indexOfKey(*handle);
2999 if (index >= 0) {
3000 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3001 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3002 }
3003 patchDesc = mAudioPatches.valueAt(index);
3004 patchDesc->mUid = uid;
3005 ALOGV("createAudioPatch() success");
3006 } else {
3007 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3008 return INVALID_OPERATION;
3009 }
3010 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3011 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3012 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003013 // only one sink supported when connecting an input device to a mix
3014 if (patch->num_sinks > 1) {
3015 return INVALID_OPERATION;
3016 }
François Gaffie53615e22015-03-19 09:24:12 +01003017 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003018 if (inputDesc == NULL) {
3019 return BAD_VALUE;
3020 }
3021 if (patchDesc != 0) {
3022 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3023 return BAD_VALUE;
3024 }
3025 }
3026 sp<DeviceDescriptor> devDesc =
3027 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3028 if (devDesc == 0) {
3029 return BAD_VALUE;
3030 }
3031
François Gaffie53615e22015-03-19 09:24:12 +01003032 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003033 devDesc->mAddress,
3034 patch->sinks[0].sample_rate,
3035 NULL, /*updatedSampleRate*/
3036 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003037 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003038 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003039 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003040 // FIXME for the parameter type,
3041 // and the NONE
3042 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003043 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 return INVALID_OPERATION;
3045 }
3046 // TODO: reconfigure output format and channels here
3047 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003048 devDesc->type(), inputDesc->mIoHandle);
3049 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 index = mAudioPatches.indexOfKey(*handle);
3051 if (index >= 0) {
3052 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3053 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3054 }
3055 patchDesc = mAudioPatches.valueAt(index);
3056 patchDesc->mUid = uid;
3057 ALOGV("createAudioPatch() success");
3058 } else {
3059 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3060 return INVALID_OPERATION;
3061 }
3062 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3063 // device to device connection
3064 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003065 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 return BAD_VALUE;
3067 }
3068 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003069 sp<DeviceDescriptor> srcDeviceDesc =
3070 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003071 if (srcDeviceDesc == 0) {
3072 return BAD_VALUE;
3073 }
Eric Laurent874c42872014-08-08 15:13:39 -07003074
Eric Laurent6a94d692014-05-20 11:18:06 -07003075 //update source and sink with our own data as the data passed in the patch may
3076 // be incomplete.
3077 struct audio_patch newPatch = *patch;
3078 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003079
Eric Laurent874c42872014-08-08 15:13:39 -07003080 for (size_t i = 0; i < patch->num_sinks; i++) {
3081 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3082 ALOGV("createAudioPatch() source device but one sink is not a device");
3083 return INVALID_OPERATION;
3084 }
3085
3086 sp<DeviceDescriptor> sinkDeviceDesc =
3087 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3088 if (sinkDeviceDesc == 0) {
3089 return BAD_VALUE;
3090 }
3091 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3092
Eric Laurent3bcf8592015-04-03 12:13:24 -07003093 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003094 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003095 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003096 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003097 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003098 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003099 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003100 return INVALID_OPERATION;
3101 }
Eric Laurent874c42872014-08-08 15:13:39 -07003102 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003103 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003104 // if the sink device is reachable via an opened output stream, request to go via
3105 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003106 audio_io_handle_t output = selectOutput(outputs,
3107 AUDIO_OUTPUT_FLAG_NONE,
3108 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003109 if (output != AUDIO_IO_HANDLE_NONE) {
3110 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3111 if (outputDesc->isDuplicated()) {
3112 return INVALID_OPERATION;
3113 }
3114 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003115 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003116 newPatch.num_sources = 2;
3117 }
Eric Laurent83b88082014-06-20 18:31:16 -07003118 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003119 }
3120 // TODO: check from routing capabilities in config file and other conflicting patches
3121
Mikhail Naganovdc769682018-05-04 15:34:08 -07003122 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3123 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3125 status);
3126 return INVALID_OPERATION;
3127 }
3128 } else {
3129 return BAD_VALUE;
3130 }
3131 } else {
3132 return BAD_VALUE;
3133 }
3134 return NO_ERROR;
3135}
3136
3137status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3138 uid_t uid)
3139{
3140 ALOGV("releaseAudioPatch() patch %d", handle);
3141
3142 ssize_t index = mAudioPatches.indexOfKey(handle);
3143
3144 if (index < 0) {
3145 return BAD_VALUE;
3146 }
3147 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3148 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3149 mUidCached, patchDesc->mUid, uid);
3150 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3151 return INVALID_OPERATION;
3152 }
3153
3154 struct audio_patch *patch = &patchDesc->mPatch;
3155 patchDesc->mUid = mUidCached;
3156 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003157 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003158 if (outputDesc == NULL) {
3159 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3160 return BAD_VALUE;
3161 }
3162
Eric Laurentc75307b2015-03-17 15:29:32 -07003163 setOutputDevice(outputDesc,
3164 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 true,
3166 0,
3167 NULL);
3168 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3169 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003170 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003171 if (inputDesc == NULL) {
3172 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3173 return BAD_VALUE;
3174 }
3175 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003176 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003177 true,
3178 NULL);
3179 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003180 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3181 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3182 status, patchDesc->mAfPatchHandle);
3183 removeAudioPatch(patchDesc->mHandle);
3184 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003185 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003186 } else {
3187 return BAD_VALUE;
3188 }
3189 } else {
3190 return BAD_VALUE;
3191 }
3192 return NO_ERROR;
3193}
3194
3195status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3196 struct audio_patch *patches,
3197 unsigned int *generation)
3198{
François Gaffie53615e22015-03-19 09:24:12 +01003199 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 return BAD_VALUE;
3201 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003202 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003203 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003204}
3205
Eric Laurente1715a42014-05-20 11:30:42 -07003206status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003207{
Eric Laurente1715a42014-05-20 11:30:42 -07003208 ALOGV("setAudioPortConfig()");
3209
3210 if (config == NULL) {
3211 return BAD_VALUE;
3212 }
3213 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3214 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003215 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3216 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003217 }
3218
Eric Laurenta121f902014-06-03 13:32:54 -07003219 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003220 if (config->type == AUDIO_PORT_TYPE_MIX) {
3221 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003222 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003223 if (outputDesc == NULL) {
3224 return BAD_VALUE;
3225 }
Eric Laurent84c70242014-06-23 08:46:27 -07003226 ALOG_ASSERT(!outputDesc->isDuplicated(),
3227 "setAudioPortConfig() called on duplicated output %d",
3228 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003229 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003230 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003231 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003232 if (inputDesc == NULL) {
3233 return BAD_VALUE;
3234 }
Eric Laurenta121f902014-06-03 13:32:54 -07003235 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003236 } else {
3237 return BAD_VALUE;
3238 }
3239 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3240 sp<DeviceDescriptor> deviceDesc;
3241 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3242 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3243 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3244 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3245 } else {
3246 return BAD_VALUE;
3247 }
3248 if (deviceDesc == NULL) {
3249 return BAD_VALUE;
3250 }
Eric Laurenta121f902014-06-03 13:32:54 -07003251 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003252 } else {
3253 return BAD_VALUE;
3254 }
3255
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003256 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003257 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3258 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003259 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003260 audioPortConfig->toAudioPortConfig(&newConfig, config);
3261 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003262 }
Eric Laurenta121f902014-06-03 13:32:54 -07003263 if (status != NO_ERROR) {
3264 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003265 }
Eric Laurente1715a42014-05-20 11:30:42 -07003266
3267 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003268}
3269
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003270void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3271{
Eric Laurentd60560a2015-04-10 11:31:20 -07003272 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003273 clearAudioPatches(uid);
3274 clearSessionRoutes(uid);
3275}
3276
Eric Laurent6a94d692014-05-20 11:18:06 -07003277void AudioPolicyManager::clearAudioPatches(uid_t uid)
3278{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003279 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003280 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3281 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003282 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003283 }
3284 }
3285}
3286
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003287void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3288 audio_io_handle_t ouptutToSkip)
3289{
3290 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3291 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3292 for (size_t j = 0; j < mOutputs.size(); j++) {
3293 if (mOutputs.keyAt(j) == ouptutToSkip) {
3294 continue;
3295 }
3296 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3297 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3298 continue;
3299 }
3300 // If the default device for this strategy is on another output mix,
3301 // invalidate all tracks in this strategy to force re connection.
3302 // Otherwise select new device on the output mix.
3303 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003304 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003305 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3306 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3307 }
3308 }
3309 } else {
3310 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3311 setOutputDevice(outputDesc, newDevice, false);
3312 }
3313 }
3314}
3315
3316void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3317{
3318 // remove output routes associated with this uid
3319 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003320 for (size_t i = 0; i < mOutputs.size(); i++) {
3321 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003322 for (const auto& client : outputDesc->getClientIterable()) {
3323 if (client->hasPreferredDevice() && client->uid() == uid) {
3324 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3325 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003326 }
3327 }
3328 }
3329 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003330 for (const auto& strategy : affectedStrategies) {
3331 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003332 }
3333
3334 // remove input routes associated with this uid
3335 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003336 for (size_t i = 0; i < mInputs.size(); i++) {
3337 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003338 for (const auto& client : inputDesc->getClientIterable()) {
3339 if (client->hasPreferredDevice() && client->uid() == uid) {
3340 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3341 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003342 }
3343 }
3344 }
3345 // reroute inputs if necessary
3346 SortedVector<audio_io_handle_t> inputsToClose;
3347 for (size_t i = 0; i < mInputs.size(); i++) {
3348 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003349 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003350 inputsToClose.add(inputDesc->mIoHandle);
3351 }
3352 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003353 for (const auto& input : inputsToClose) {
3354 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003355 }
3356}
3357
Eric Laurentd60560a2015-04-10 11:31:20 -07003358void AudioPolicyManager::clearAudioSources(uid_t uid)
3359{
3360 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003361 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3362 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003363 stopAudioSource(mAudioSources.keyAt(i));
3364 }
3365 }
3366}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003367
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003368status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3369 audio_io_handle_t *ioHandle,
3370 audio_devices_t *device)
3371{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003372 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3373 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003374 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003375
François Gaffiedf372692015-03-19 10:43:27 +01003376 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003377}
3378
Eric Laurentd60560a2015-04-10 11:31:20 -07003379status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003380 const audio_attributes_t *attributes,
3381 audio_port_handle_t *portId,
3382 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003383{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003384 ALOGV("%s", __FUNCTION__);
3385 *portId = AUDIO_PORT_HANDLE_NONE;
3386
3387 if (source == NULL || attributes == NULL || portId == NULL) {
3388 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3389 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003390 return BAD_VALUE;
3391 }
3392
Eric Laurentd60560a2015-04-10 11:31:20 -07003393 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3394 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003395 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3396 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003397 return INVALID_OPERATION;
3398 }
3399
3400 sp<DeviceDescriptor> srcDeviceDesc =
3401 mAvailableInputDevices.getDevice(source->ext.device.type,
3402 String8(source->ext.device.address));
3403 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003404 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003405 return BAD_VALUE;
3406 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003407
3408 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003409
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003410 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003411 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003412
3413 sp<SourceClientDescriptor> sourceDesc =
3414 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003415 streamTypefromAttributesInt(attributes),
3416 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003417
3418 status_t status = connectAudioSource(sourceDesc);
3419 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003420 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003421 }
3422 return status;
3423}
3424
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003425status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003426{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003427 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003428
3429 // make sure we only have one patch per source.
3430 disconnectAudioSource(sourceDesc);
3431
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003432 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003433 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003434 audio_stream_type_t stream = sourceDesc->stream();
3435 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003436
3437 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3438 sp<DeviceDescriptor> sinkDeviceDesc =
3439 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3440
3441 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003442
3443 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3444 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003445 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003446 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3447 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3448 // create patch between src device and output device
3449 // create Hwoutput and add to mHwOutputs
3450 } else {
3451 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3452 audio_io_handle_t output =
3453 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3454 if (output == AUDIO_IO_HANDLE_NONE) {
3455 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3456 return INVALID_OPERATION;
3457 }
3458 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3459 if (outputDesc->isDuplicated()) {
3460 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3461 return INVALID_OPERATION;
3462 }
Eric Laurent733ce942017-12-07 12:18:25 -08003463 status_t status = outputDesc->start();
3464 if (status != NO_ERROR) {
3465 return status;
3466 }
3467
Eric Laurentd60560a2015-04-10 11:31:20 -07003468 // create a special patch with no sink and two sources:
3469 // - the second source indicates to PatchPanel through which output mix this patch should
3470 // be connected as well as the stream type for volume control
3471 // - the sink is defined by whatever output device is currently selected for the output
3472 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003473 PatchBuilder patchBuilder;
3474 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3475 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003476 &afPatchHandle,
3477 0);
3478 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3479 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003480 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003481 if (status != NO_ERROR) {
3482 ALOGW("%s patch panel could not connect device patch, error %d",
3483 __FUNCTION__, status);
3484 return INVALID_OPERATION;
3485 }
3486 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003487 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003488
3489 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003490 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003491 return status;
3492 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003493 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003494 if (delayMs != 0) {
3495 usleep(delayMs * 1000);
3496 }
3497 }
3498
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3500 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003501
3502 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003503}
3504
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003505status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003506{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003507 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3508 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003509 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003510 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003511 return BAD_VALUE;
3512 }
3513 status_t status = disconnectAudioSource(sourceDesc);
3514
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003515 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003516 return status;
3517}
3518
Andy Hung2ddee192015-12-18 17:34:44 -08003519status_t AudioPolicyManager::setMasterMono(bool mono)
3520{
3521 if (mMasterMono == mono) {
3522 return NO_ERROR;
3523 }
3524 mMasterMono = mono;
3525 // if enabling mono we close all offloaded devices, which will invalidate the
3526 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3527 // for recreating the new AudioTrack as non-offloaded PCM.
3528 //
3529 // If disabling mono, we leave all tracks as is: we don't know which clients
3530 // and tracks are able to be recreated as offloaded. The next "song" should
3531 // play back offloaded.
3532 if (mMasterMono) {
3533 Vector<audio_io_handle_t> offloaded;
3534 for (size_t i = 0; i < mOutputs.size(); ++i) {
3535 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3536 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3537 offloaded.push(desc->mIoHandle);
3538 }
3539 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003540 for (const auto& handle : offloaded) {
3541 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003542 }
3543 }
3544 // update master mono for all remaining outputs
3545 for (size_t i = 0; i < mOutputs.size(); ++i) {
3546 updateMono(mOutputs.keyAt(i));
3547 }
3548 return NO_ERROR;
3549}
3550
3551status_t AudioPolicyManager::getMasterMono(bool *mono)
3552{
3553 *mono = mMasterMono;
3554 return NO_ERROR;
3555}
3556
Eric Laurentac9cef52017-06-09 15:46:26 -07003557float AudioPolicyManager::getStreamVolumeDB(
3558 audio_stream_type_t stream, int index, audio_devices_t device)
3559{
3560 return computeVolume(stream, index, device);
3561}
3562
jiabin81772902018-04-02 17:52:27 -07003563status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3564 audio_format_t *surroundFormats,
3565 bool *surroundFormatsEnabled,
3566 bool reported)
3567{
3568 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3569 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3570 return BAD_VALUE;
3571 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003572 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3573 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003574
3575 // Only return value if there is HDMI output.
3576 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3577 return INVALID_OPERATION;
3578 }
3579
3580 size_t formatsWritten = 0;
3581 size_t formatsMax = *numSurroundFormats;
3582 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003583 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003584 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003585 // Return formats from HDMI profiles, that have already been resolved by
3586 // checkOutputsForDevice().
3587 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3588 AUDIO_DEVICE_OUT_HDMI);
3589 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3590 FormatVector supportedFormats =
3591 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3592 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003593 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003594 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003595 } else {
3596 for (const auto& pair : mConfig.getSurroundFormats()) {
3597 if (pair.second.count(supportedFormats[j]) != 0) {
3598 formats.insert(pair.first);
3599 break;
3600 }
3601 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003602 }
3603 }
jiabin81772902018-04-02 17:52:27 -07003604 }
3605 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003606 for (const auto& pair : mConfig.getSurroundFormats()) {
3607 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003608 }
3609 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003610 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003611 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003612 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003613 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003614 if (mConfig.getSurroundFormats().count(format) == 0) {
3615 // Check sub-formats
3616 for (const auto& pair : mConfig.getSurroundFormats()) {
3617 for (const auto& subformat : pair.second) {
3618 formatEnabled = mSurroundFormats.count(subformat) != 0;
3619 if (formatEnabled) break;
3620 }
3621 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003622 }
3623 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003624 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003625 }
3626 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3627 }
3628 (*numSurroundFormats)++;
3629 }
3630 return NO_ERROR;
3631}
3632
3633status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3634{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003635 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003636 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003637 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3638 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003639 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003640 return BAD_VALUE;
3641 }
3642
3643 // Should only be called when MANUAL.
3644 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3645 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3646 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003647 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003648 return INVALID_OPERATION;
3649 }
3650
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003651 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003652 return NO_ERROR;
3653 }
3654
3655 // The operation is valid only when there is HDMI output available.
3656 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003657 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003658 return INVALID_OPERATION;
3659 }
3660
Mikhail Naganov2563f232018-09-27 14:48:01 -07003661 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003662 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003663 mSurroundFormats.insert(audioFormat);
3664 for (const auto& subFormat : formatIter->second) {
3665 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003666 }
3667 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003668 mSurroundFormats.erase(audioFormat);
3669 for (const auto& subFormat : formatIter->second) {
3670 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003671 }
3672 }
3673
3674 sp<SwAudioOutputDescriptor> outputDesc;
3675 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003676 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003677 AUDIO_DEVICE_OUT_HDMI);
3678 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3679 // Simulate reconnection to update enabled surround sound formats.
3680 String8 address = hdmiOutputDevices[i]->mAddress;
3681 String8 name = hdmiOutputDevices[i]->getName();
3682 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3683 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3684 address.c_str(),
3685 name.c_str());
3686 if (status != NO_ERROR) {
3687 continue;
3688 }
3689 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3690 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3691 address.c_str(),
3692 name.c_str());
3693 profileUpdated |= (status == NO_ERROR);
3694 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003695 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003696 AUDIO_DEVICE_IN_HDMI);
3697 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3698 // Simulate reconnection to update enabled surround sound formats.
3699 String8 address = hdmiInputDevices[i]->mAddress;
3700 String8 name = hdmiInputDevices[i]->getName();
3701 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3702 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3703 address.c_str(),
3704 name.c_str());
3705 if (status != NO_ERROR) {
3706 continue;
3707 }
3708 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3709 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3710 address.c_str(),
3711 name.c_str());
3712 profileUpdated |= (status == NO_ERROR);
3713 }
3714
jiabin81772902018-04-02 17:52:27 -07003715 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003716 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003717 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003718 }
3719
3720 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3721}
3722
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003723void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3724{
3725 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3726
3727 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3728 for (size_t i = 0; i < activeInputs.size(); i++) {
3729 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003730 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3731 for (const auto& client : clients) {
3732 if (uid == client->uid()) {
3733 client->setSilenced(silenced);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003734 }
3735 }
3736 }
3737}
3738
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003739status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003740{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003741 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003742
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003743 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003744 if (patchDesc == 0) {
3745 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003746 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003747 return BAD_VALUE;
3748 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003749 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003750
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003751 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003752 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003753 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003754 if (status == NO_ERROR) {
3755 swOutputDesc->stop();
3756 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003757 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3758 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003759 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003760 if (hwOutputDesc != 0) {
3761 // release patch between src device and output device
3762 // close Hwoutput and remove from mHwOutputs
3763 } else {
3764 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3765 }
3766 }
3767 return NO_ERROR;
3768}
3769
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003770sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003771 audio_io_handle_t output, routing_strategy strategy)
3772{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003773 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003774 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003775 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3776 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003777 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003778 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003779 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3780 source = sourceDesc;
3781 break;
3782 }
3783 }
3784 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003785}
3786
Eric Laurente552edb2014-03-10 17:42:56 -07003787// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003788// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003789// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003790uint32_t AudioPolicyManager::nextAudioPortGeneration()
3791{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003792 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003793}
3794
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003795#ifdef USE_XML_AUDIO_POLICY_CONF
3796// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3797static const char *kConfigLocationList[] =
3798 {"/odm/etc", "/vendor/etc", "/system/etc"};
3799static const int kConfigLocationListSize =
3800 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3801
3802static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3803 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003804 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003805 status_t ret;
3806
Petri Gyntherf497f292018-04-17 18:46:10 -07003807 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3808 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3809 // A2DP offload supported but disabled: try to use special XML file
3810 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3811 }
3812 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3813
3814 for (const char* fileName : fileNames) {
3815 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003816 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3817 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003818 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003819 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003820 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003821 return ret;
3822 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003823 }
3824 }
3825 return ret;
3826}
3827#endif
3828
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003829AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3830 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003831 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003832 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003833 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003834 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003835 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003836#ifdef USE_XML_AUDIO_POLICY_CONF
3837 mVolumeCurves(new VolumeCurvesCollection()),
3838 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003839 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003840#else
3841 mVolumeCurves(new StreamDescriptorCollection()),
3842 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3843 mDefaultOutputDevice),
3844#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003845 mAudioPortGeneration(1),
3846 mBeaconMuteRefCount(0),
3847 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003848 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003849 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003850 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003851 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3852 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003853{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003854}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003855
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003856AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3857 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3858{
3859 loadConfig();
3860 initialize();
3861}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003862
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003864#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003866#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003867 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3868 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003869#endif
3870 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003871 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873}
3874
3875status_t AudioPolicyManager::initialize() {
3876 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003877
3878 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003879 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3880 if (!engineInstance) {
3881 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003882 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003883 }
3884 // Retrieve the Policy Manager Interface
3885 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3886 if (mEngine == NULL) {
3887 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003889 }
3890 mEngine->setObserver(this);
3891 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892 if (status != NO_ERROR) {
3893 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3894 return status;
3895 }
François Gaffie2110e042015-03-24 08:41:51 +01003896
Eric Laurent3a4311c2014-03-17 12:00:47 -07003897 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003898 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003899 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3900 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003901 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003902 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003903 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3904 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003905 continue;
3906 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003907 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003908 // open all output streams needed to access attached devices
3909 // except for direct output streams that are only opened when they are actually
3910 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003911 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003912 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003913 if (!outProfile->canOpenNewIo()) {
3914 ALOGE("Invalid Output profile max open count %u for profile %s",
3915 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3916 continue;
3917 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003918 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003919 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003920 continue;
3921 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003922 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003923 mTtsOutputAvailable = true;
3924 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003926 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003927 continue;
3928 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003929 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003930 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3931 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003932 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003933 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003934 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003935 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003936 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003937 if ((profileType & outputDeviceTypes) == 0) {
3938 continue;
3939 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003940 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3941 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003942 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003943 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3944 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003945 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3946 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003947 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003948 status_t status = outputDesc->open(nullptr, profileType, address,
3949 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003950
3951 if (status != NO_ERROR) {
3952 ALOGW("Cannot open output stream for device %08x on hw module %s",
3953 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003954 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003955 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003956 for (const auto& dev : supportedDevices) {
3957 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003958 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003959 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003960 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003961 }
3962 }
3963 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003964 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003965 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003966 }
3967 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003968 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003969 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003970 true,
3971 0,
3972 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003973 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003974 }
Eric Laurente552edb2014-03-10 17:42:56 -07003975 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003976 // open input streams needed to access attached devices to validate
3977 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003978 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003979 if (!inProfile->canOpenNewIo()) {
3980 ALOGE("Invalid Input profile max open count %u for profile %s",
3981 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3982 continue;
3983 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003985 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 continue;
3987 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003988 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003989 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3991
Eric Laurentd78f1532014-09-16 16:38:20 -07003992 if ((profileType & inputDeviceTypes) == 0) {
3993 continue;
3994 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003995 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003996 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003997
Mikhail Naganov708e0382018-05-30 09:53:04 -07003998 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003999 // the inputs vector must be of size >= 1, but we don't want to crash here
4000 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4001 : String8("");
4002 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4003 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4004
Eric Laurentd78f1532014-09-16 16:38:20 -07004005 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004006 status_t status = inputDesc->open(nullptr,
4007 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004008 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004009 AUDIO_SOURCE_MIC,
4010 AUDIO_INPUT_FLAG_NONE,
4011 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004012
4013 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004014 for (const auto& dev : inProfile->getSupportedDevices()) {
4015 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004016 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004017 if (index >= 0) {
4018 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4019 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004020 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004021 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004022 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004023 }
4024 }
Eric Laurentfe231122017-11-17 17:48:06 -08004025 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004026 } else {
4027 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004028 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004029 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004030 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004031 }
4032 }
4033 // make sure all attached devices have been allocated a unique ID
4034 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004035 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004036 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004037 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4038 continue;
4039 }
François Gaffie2110e042015-03-24 08:41:51 +01004040 // The device is now validated and can be appended to the available devices of the engine
4041 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4042 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 i++;
4044 }
4045 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004046 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004047 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004048 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4049 continue;
4050 }
François Gaffie2110e042015-03-24 08:41:51 +01004051 // The device is now validated and can be appended to the available devices of the engine
4052 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4053 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004054 i++;
4055 }
4056 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004057 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004058 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004059 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 }
jiabin9ff780e2018-03-19 18:19:52 -07004061 // If microphones address is empty, set it according to device type
4062 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4063 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4064 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4065 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4066 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4067 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4068 }
4069 }
4070 }
Eric Laurente552edb2014-03-10 17:42:56 -07004071
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004072 if (mPrimaryOutput == 0) {
4073 ALOGE("Failed to open primary output");
4074 status = NO_INIT;
4075 }
Eric Laurente552edb2014-03-10 17:42:56 -07004076
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004077 // Silence ALOGV statements
4078 property_set("log.tag." LOG_TAG, "D");
4079
Eric Laurente552edb2014-03-10 17:42:56 -07004080 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004081 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004082}
4083
Eric Laurente0720872014-03-11 09:30:41 -07004084AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004085{
Eric Laurente552edb2014-03-10 17:42:56 -07004086 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004087 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004088 }
4089 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004090 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004091 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092 mAvailableOutputDevices.clear();
4093 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004094 mOutputs.clear();
4095 mInputs.clear();
4096 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004097 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004098 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004099}
4100
Eric Laurente0720872014-03-11 09:30:41 -07004101status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004102{
Eric Laurent87ffa392015-05-22 10:32:38 -07004103 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004104}
4105
Eric Laurente552edb2014-03-10 17:42:56 -07004106// ---
4107
Eric Laurent98e38192018-02-15 18:31:53 -08004108void AudioPolicyManager::addOutput(audio_io_handle_t output,
4109 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004110{
Eric Laurent1c333e22014-05-20 10:48:17 -07004111 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004112 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004113 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004114 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004115 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004116}
4117
François Gaffie53615e22015-03-19 09:24:12 +01004118void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4119{
4120 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004121 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004122}
4123
Eric Laurent98e38192018-02-15 18:31:53 -08004124void AudioPolicyManager::addInput(audio_io_handle_t input,
4125 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004126{
Eric Laurent1c333e22014-05-20 10:48:17 -07004127 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004129}
Eric Laurente552edb2014-03-10 17:42:56 -07004130
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004131void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004132 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004133 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004134 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004135 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004136 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004137 if (devDesc != 0) {
4138 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4139 desc->mIoHandle, address.string());
4140 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004141 }
4142}
4143
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004144status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004145 audio_policy_dev_state_t state,
4146 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004147 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004148{
François Gaffie53615e22015-03-19 09:24:12 +01004149 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004150 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004151
4152 if (audio_device_is_digital(device)) {
4153 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004154 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004155 }
Eric Laurente552edb2014-03-10 17:42:56 -07004156
Eric Laurent3b73df72014-03-11 09:06:29 -07004157 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004158 // first list already open outputs that can be routed to this device
4159 for (size_t i = 0; i < mOutputs.size(); i++) {
4160 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004161 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004162 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4164 outputs.add(mOutputs.keyAt(i));
4165 } else {
4166 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004167 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004168 }
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170 }
4171 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004172 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004173 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004174 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4175 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004176 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004177 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004178 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004179 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004180 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4181 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004182 }
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
4184 }
4185 }
4186
Eric Laurent7b279bb2015-12-14 10:18:23 -08004187 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004188
Eric Laurente552edb2014-03-10 17:42:56 -07004189 if (profiles.isEmpty() && outputs.isEmpty()) {
4190 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4191 return BAD_VALUE;
4192 }
4193
4194 // open outputs for matching profiles if needed. Direct outputs are also opened to
4195 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4196 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004197 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004198
4199 // nothing to do if one output is already opened for this profile
4200 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004201 for (j = 0; j < outputs.size(); j++) {
4202 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004203 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004204 // matching profile: save the sample rates, format and channel masks supported
4205 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004206 if (audio_device_is_digital(device)) {
4207 devDesc->importAudioPort(profile);
4208 }
Eric Laurente552edb2014-03-10 17:42:56 -07004209 break;
4210 }
4211 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004212 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004213 continue;
4214 }
4215
Eric Laurent3974e3b2017-12-07 17:58:43 -08004216 if (!profile->canOpenNewIo()) {
4217 ALOGW("Max Output number %u already opened for this profile %s",
4218 profile->maxOpenCount, profile->getTagName().c_str());
4219 continue;
4220 }
4221
Eric Laurent83efe1c2017-07-09 16:51:08 -07004222 ALOGV("opening output for device %08x with params %s profile %p name %s",
4223 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004224 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004225 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004226 status_t status = desc->open(nullptr, device, address,
4227 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004228
Eric Laurentfe231122017-11-17 17:48:06 -08004229 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004230 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004231 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004232 char *param = audio_device_address_to_parameter(device, address);
4233 mpClientInterface->setParameters(output, String8(param));
4234 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004235 }
Phil Burk00eeb322016-03-31 12:41:00 -07004236 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004237 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004238 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004239 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004240 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004241 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004242 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004243 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004244 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4245 profile->pickAudioProfile(
4246 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004247 config.offload_info.sample_rate = config.sample_rate;
4248 config.offload_info.channel_mask = config.channel_mask;
4249 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004250
4251 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4252 AUDIO_OUTPUT_FLAG_NONE, &output);
4253 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 output = AUDIO_IO_HANDLE_NONE;
4255 }
Eric Laurentd4692962014-05-05 18:13:44 -07004256 }
4257
Eric Laurentcf2c0212014-07-25 16:20:43 -07004258 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004259 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004260 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004261 sp<AudioPolicyMix> policyMix;
4262 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004263 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4264 address.string());
4265 }
François Gaffie036e1e92015-03-19 10:16:24 +01004266 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004267 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004268
Eric Laurent87ffa392015-05-22 10:32:38 -07004269 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4270 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004271 // no duplicated output for direct outputs and
4272 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004273 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004274
Eric Laurentd4692962014-05-05 18:13:44 -07004275 //TODO: configure audio effect output stage here
4276
4277 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004278 sp<SwAudioOutputDescriptor> dupOutputDesc =
4279 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4280 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4281 &duplicatedOutput);
4282 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004283 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004284 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004285 } else {
4286 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004287 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004288 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004289 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004290 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004291 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004292 }
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004295 } else {
4296 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004297 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004298 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004299 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004300 profiles.removeAt(profile_index);
4301 profile_index--;
4302 } else {
4303 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004304 // Load digital format info only for digital devices
4305 if (audio_device_is_digital(device)) {
4306 devDesc->importAudioPort(profile);
4307 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004308
François Gaffie53615e22015-03-19 09:24:12 +01004309 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004310 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4311 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004312 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004313 NULL/*patch handle*/, address.string());
4314 }
Eric Laurente552edb2014-03-10 17:42:56 -07004315 ALOGV("checkOutputsForDevice(): adding output %d", output);
4316 }
4317 }
4318
4319 if (profiles.isEmpty()) {
4320 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4321 return BAD_VALUE;
4322 }
Eric Laurentd4692962014-05-05 18:13:44 -07004323 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004324 // check if one opened output is not needed any more after disconnecting one device
4325 for (size_t i = 0; i < mOutputs.size(); i++) {
4326 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004327 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004328 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004329 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004330 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004331 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004332 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004333 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4334 mOutputs.keyAt(i));
4335 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004336 }
Eric Laurente552edb2014-03-10 17:42:56 -07004337 }
4338 }
Eric Laurentd4692962014-05-05 18:13:44 -07004339 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004340 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004341 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4342 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004343 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004344 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004345 "clearing direct output profile %zu on module %s",
4346 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004347 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004348 }
4349 }
4350 }
4351 }
4352 return NO_ERROR;
4353}
4354
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004355status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004356 audio_policy_dev_state_t state,
4357 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004358 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004359{
Paul McLean9080a4c2015-06-18 08:24:02 -07004360 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004361 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004362
4363 if (audio_device_is_digital(device)) {
4364 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004365 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004366 }
4367
Eric Laurentd4692962014-05-05 18:13:44 -07004368 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4369 // first list already open inputs that can be routed to this device
4370 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4371 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004372 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004373 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4374 inputs.add(mInputs.keyAt(input_index));
4375 }
4376 }
4377
4378 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004379 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004380 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004381 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004382 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004383 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004384 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004385
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004386 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004387 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004388 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004389 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004390 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4391 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004392 }
Eric Laurentd4692962014-05-05 18:13:44 -07004393 }
4394 }
4395 }
4396
4397 if (profiles.isEmpty() && inputs.isEmpty()) {
4398 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4399 return BAD_VALUE;
4400 }
4401
4402 // open inputs for matching profiles if needed. Direct inputs are also opened to
4403 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4404 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4405
Eric Laurent1c333e22014-05-20 10:48:17 -07004406 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004407
Eric Laurentd4692962014-05-05 18:13:44 -07004408 // nothing to do if one input is already opened for this profile
4409 size_t input_index;
4410 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4411 desc = mInputs.valueAt(input_index);
4412 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004413 if (audio_device_is_digital(device)) {
4414 devDesc->importAudioPort(profile);
4415 }
Eric Laurentd4692962014-05-05 18:13:44 -07004416 break;
4417 }
4418 }
4419 if (input_index != mInputs.size()) {
4420 continue;
4421 }
4422
Eric Laurent3974e3b2017-12-07 17:58:43 -08004423 if (!profile->canOpenNewIo()) {
4424 ALOGW("Max Input number %u already opened for this profile %s",
4425 profile->maxOpenCount, profile->getTagName().c_str());
4426 continue;
4427 }
4428
Eric Laurentfe231122017-11-17 17:48:06 -08004429 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004430 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004431 status_t status = desc->open(nullptr,
4432 device,
4433 address,
4434 AUDIO_SOURCE_MIC,
4435 AUDIO_INPUT_FLAG_NONE,
4436 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004437
Eric Laurentcf2c0212014-07-25 16:20:43 -07004438 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004439 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004440 char *param = audio_device_address_to_parameter(device, address);
4441 mpClientInterface->setParameters(input, String8(param));
4442 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004443 }
Phil Burk00eeb322016-03-31 12:41:00 -07004444 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004445 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004446 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004447 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004448 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004449 }
4450
4451 if (input != 0) {
4452 addInput(input, desc);
4453 }
4454 } // endif input != 0
4455
Eric Laurentcf2c0212014-07-25 16:20:43 -07004456 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004457 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004458 profiles.removeAt(profile_index);
4459 profile_index--;
4460 } else {
4461 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004462 if (audio_device_is_digital(device)) {
4463 devDesc->importAudioPort(profile);
4464 }
Eric Laurentd4692962014-05-05 18:13:44 -07004465 ALOGV("checkInputsForDevice(): adding input %d", input);
4466 }
4467 } // end scan profiles
4468
4469 if (profiles.isEmpty()) {
4470 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4471 return BAD_VALUE;
4472 }
4473 } else {
4474 // Disconnect
4475 // check if one opened input is not needed any more after disconnecting one device
4476 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4477 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004478 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004479 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4480 mInputs.keyAt(input_index));
4481 inputs.add(mInputs.keyAt(input_index));
4482 }
4483 }
4484 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004485 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004487 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004488 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004489 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004490 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004491 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4492 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004493 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004494 }
4495 }
4496 }
4497 } // end disconnect
4498
4499 return NO_ERROR;
4500}
4501
4502
Eric Laurente0720872014-03-11 09:30:41 -07004503void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004504{
4505 ALOGV("closeOutput(%d)", output);
4506
Eric Laurentc75307b2015-03-17 15:29:32 -07004507 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004508 if (outputDesc == NULL) {
4509 ALOGW("closeOutput() unknown output %d", output);
4510 return;
4511 }
François Gaffie036e1e92015-03-19 10:16:24 +01004512 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004513
Eric Laurente552edb2014-03-10 17:42:56 -07004514 // look for duplicated outputs connected to the output being removed.
4515 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004516 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004517 if (dupOutputDesc->isDuplicated() &&
4518 (dupOutputDesc->mOutput1 == outputDesc ||
4519 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004520 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004521 if (dupOutputDesc->mOutput1 == outputDesc) {
4522 outputDesc2 = dupOutputDesc->mOutput2;
4523 } else {
4524 outputDesc2 = dupOutputDesc->mOutput1;
4525 }
4526 // As all active tracks on duplicated output will be deleted,
4527 // and as they were also referenced on the other output, the reference
4528 // count for their stream type must be adjusted accordingly on
4529 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004530 const bool wasActive = outputDesc2->isActive();
4531 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4532 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004533 }
Eric Laurent733ce942017-12-07 12:18:25 -08004534 // stop() will be a no op if the output is still active but is needed in case all
4535 // active streams refcounts where cleared above
4536 if (wasActive) {
4537 outputDesc2->stop();
4538 }
Eric Laurente552edb2014-03-10 17:42:56 -07004539 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4540 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4541
4542 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004543 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004544 }
4545 }
4546
Eric Laurent05b90f82014-08-27 15:32:29 -07004547 nextAudioPortGeneration();
4548
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004549 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004550 if (index >= 0) {
4551 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004552 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004553 mAudioPatches.removeItemsAt(index);
4554 mpClientInterface->onAudioPatchListUpdate();
4555 }
4556
Eric Laurentfe231122017-11-17 17:48:06 -08004557 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004558
François Gaffie53615e22015-03-19 09:24:12 +01004559 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004560 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004561
4562 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4563 // no direct outputs are open.
4564 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4565 bool directOutputOpen = false;
4566 for (size_t i = 0; i < mOutputs.size(); i++) {
4567 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4568 directOutputOpen = true;
4569 break;
4570 }
4571 }
4572 if (!directOutputOpen) {
4573 ALOGV("no direct outputs open, reset MSD patch");
4574 setMsdPatch();
4575 }
4576 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004577}
4578
4579void AudioPolicyManager::closeInput(audio_io_handle_t input)
4580{
4581 ALOGV("closeInput(%d)", input);
4582
4583 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4584 if (inputDesc == NULL) {
4585 ALOGW("closeInput() unknown input %d", input);
4586 return;
4587 }
4588
Eric Laurent6a94d692014-05-20 11:18:06 -07004589 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004590
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004591 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004592 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004593 if (index >= 0) {
4594 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004595 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004596 mAudioPatches.removeItemsAt(index);
4597 mpClientInterface->onAudioPatchListUpdate();
4598 }
4599
Eric Laurentfe231122017-11-17 17:48:06 -08004600 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004601 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004602
4603 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4604 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4605 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4606 SoundTrigger::setCaptureState(false);
4607 }
Eric Laurente552edb2014-03-10 17:42:56 -07004608}
4609
Eric Laurentc75307b2015-03-17 15:29:32 -07004610SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4611 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004612 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004613{
4614 SortedVector<audio_io_handle_t> outputs;
4615
4616 ALOGVV("getOutputsForDevice() device %04x", device);
4617 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004618 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004619 i, openOutputs.valueAt(i)->isDuplicated(),
4620 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4622 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4623 outputs.add(openOutputs.keyAt(i));
4624 }
4625 }
4626 return outputs;
4627}
4628
Mikhail Naganov37977152018-07-11 15:54:44 -07004629void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4630{
4631 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4632 // output is suspended before any tracks are moved to it
4633 checkA2dpSuspend();
4634 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004635 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004636 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004637 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004638 setMsdPatch();
4639 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004640}
4641
Eric Laurente0720872014-03-11 09:30:41 -07004642void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004643{
4644 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4645 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4646 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4647 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4648
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004649 // also take into account external policy-related changes: add all outputs which are
4650 // associated with policies in the "before" and "after" output vectors
4651 ALOGVV("checkOutputForStrategy(): policy related outputs");
4652 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004653 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004654 if (desc != 0 && desc->mPolicyMix != NULL) {
4655 srcOutputs.add(desc->mIoHandle);
4656 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4657 }
4658 }
4659 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004661 if (desc != 0 && desc->mPolicyMix != NULL) {
4662 dstOutputs.add(desc->mIoHandle);
4663 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4664 }
4665 }
4666
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004667 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004668 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4669 // audio from invalidated tracks will be rendered when unmuting
4670 uint32_t maxLatency = 0;
4671 for (audio_io_handle_t srcOut : srcOutputs) {
4672 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4673 if (desc != 0 && maxLatency < desc->latency()) {
4674 maxLatency = desc->latency();
4675 }
4676 }
Eric Laurente552edb2014-03-10 17:42:56 -07004677 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4678 strategy, srcOutputs[0], dstOutputs[0]);
4679 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004680 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004681 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4682 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004683 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004684 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004685 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004686 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004687 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004688 if (source != 0){
4689 connectAudioSource(source);
4690 }
Eric Laurente552edb2014-03-10 17:42:56 -07004691 }
4692
4693 // Move effects associated to this strategy from previous output to new output
4694 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004695 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004696 }
4697 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004698 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004699 if (getStrategy((audio_stream_type_t)i) == strategy) {
4700 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004701 }
4702 }
4703 }
4704}
4705
Eric Laurente0720872014-03-11 09:30:41 -07004706void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004707{
François Gaffie2110e042015-03-24 08:41:51 +01004708 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004709 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004710 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004711 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004712 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 checkOutputForStrategy(STRATEGY_SONIFICATION);
4714 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004715 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004716 checkOutputForStrategy(STRATEGY_MEDIA);
4717 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004718 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004719}
4720
Eric Laurente0720872014-03-11 09:30:41 -07004721void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004722{
François Gaffie53615e22015-03-19 09:24:12 +01004723 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004724 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004725 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004726 return;
4727 }
4728
Eric Laurent3a4311c2014-03-17 12:00:47 -07004729 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004730 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4731 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4732 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004733
4734 // if suspended, restore A2DP output if:
4735 // ((SCO device is NOT connected) ||
4736 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4737 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004738 //
Eric Laurentf732e072016-08-03 19:30:28 -07004739 // if not suspended, suspend A2DP output if:
4740 // (SCO device is connected) &&
4741 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4742 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004743 //
4744 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004745 if (!isScoConnected ||
4746 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4747 AUDIO_POLICY_FORCE_BT_SCO) &&
4748 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4749 AUDIO_POLICY_FORCE_BT_SCO) &&
4750 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004751 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004752
4753 mpClientInterface->restoreOutput(a2dpOutput);
4754 mA2dpSuspended = false;
4755 }
4756 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004757 if (isScoConnected &&
4758 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4759 AUDIO_POLICY_FORCE_BT_SCO) ||
4760 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4761 AUDIO_POLICY_FORCE_BT_SCO) ||
4762 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004763 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004764
4765 mpClientInterface->suspendOutput(a2dpOutput);
4766 mA2dpSuspended = true;
4767 }
4768 }
4769}
4770
Eric Laurent97ac8712018-07-27 18:59:02 -07004771template <class IoDescriptor, class Filter>
4772sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4773 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4774{
4775 auto activeClients = desc->clientsList(true /*activeOnly*/);
4776 auto activeClientsWithRoute =
4777 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4778 active = activeClients.size() > 0;
4779 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4780 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4781 }
4782 return nullptr;
4783}
4784
4785template <class IoCollection, class Filter>
4786sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4787 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4788{
4789 sp<DeviceDescriptor> device;
4790 for (size_t i = 0; i < ioCollection.size(); i++) {
4791 auto desc = ioCollection.valueAt(i);
4792 bool active;
4793 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4794 if (active && curDevice == nullptr) {
4795 return nullptr;
4796 } else if (curDevice != nullptr) {
4797 device = curDevice;
4798 }
4799 }
4800 return device;
4801}
4802
Eric Laurentc75307b2015-03-17 15:29:32 -07004803audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4804 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004805{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004806 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 if (index >= 0) {
4808 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4809 if (patchDesc->mUid != mUidCached) {
4810 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004811 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 return outputDesc->device();
4813 }
4814 }
4815
Eric Laurent97ac8712018-07-27 18:59:02 -07004816 // Honor explicit routing requests only if no client using default routing is active on this
4817 // input: a specific app can not force routing for other apps by setting a preferred device.
4818 bool active; // unused
4819 sp<DeviceDescriptor> deviceDesc =
4820 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4821 if (deviceDesc != nullptr) {
4822 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004823 }
4824
Eric Laurente552edb2014-03-10 17:42:56 -07004825 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004826 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004827 // use device for strategy enforced audible
4828 // 2: we are in call or the strategy phone is active on the output:
4829 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004830 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004831 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004832 // 4: the strategy for enforced audible is active but not enforced on the output:
4833 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004834 // 5: the strategy accessibility is active on the output:
4835 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004836 // 6: the strategy "respectful" sonification is active on the output:
4837 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004838 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004839 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004840 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004841 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004842 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004843 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004844
4845 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4846 // with a refined rule considering mutually exclusive devices (using same backend)
4847 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004848 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004849 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004850 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004851 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4852 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004853 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004855 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004857 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4858 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004859 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4860 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004861 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004862 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004863 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004865 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004866 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004867 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004868 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004869 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004870 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004871 }
4872
Eric Laurent1c333e22014-05-20 10:48:17 -07004873 ALOGV("getNewOutputDevice() selected device %x", device);
4874 return device;
4875}
4876
Eric Laurentfb66dd92016-01-28 18:32:03 -08004877audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004878{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004879 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004880
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004881 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 if (index >= 0) {
4883 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4884 if (patchDesc->mUid != mUidCached) {
4885 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004886 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 return inputDesc->mDevice;
4888 }
4889 }
4890
Eric Laurent97ac8712018-07-27 18:59:02 -07004891 // Honor explicit routing requests only if no client using default routing is active on this
4892 // input: a specific app can not force routing for other apps by setting a preferred device.
4893 bool active;
4894 sp<DeviceDescriptor> deviceDesc =
4895 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4896 if (deviceDesc != nullptr) {
4897 return deviceDesc->type();
4898 }
4899
Eric Laurentdc95a252018-04-12 12:46:56 -07004900 // If we are not in call and no client is active on this input, this methods returns
4901 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004902 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004903 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4904 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4905 }
4906 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004907 device = getDeviceAndMixForInputSource(source);
4908 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004909
Eric Laurente552edb2014-03-10 17:42:56 -07004910 return device;
4911}
4912
Eric Laurent794fde22016-03-11 09:50:45 -08004913bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4914 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004915 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004916}
4917
Eric Laurente0720872014-03-11 09:30:41 -07004918uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 return (uint32_t)getStrategy(stream);
4920}
4921
Eric Laurente0720872014-03-11 09:30:41 -07004922audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004923 // By checking the range of stream before calling getStrategy, we avoid
4924 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4925 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004926 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 return AUDIO_DEVICE_NONE;
4928 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004929 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004930 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004931 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4932 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004933 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004934 }
Eric Laurent794fde22016-03-11 09:50:45 -08004935 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004936 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004937 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004938 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004939 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4940 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004941 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004942 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004943 }
4944 }
Eric Laurente552edb2014-03-10 17:42:56 -07004945 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004946
Eric Laurentb0688d62018-08-14 15:49:18 -07004947 // Favor devices selected on active streams if any to report correct device in case of
4948 // explicit device selection
4949 if (activeDevices != AUDIO_DEVICE_NONE) {
4950 devices = activeDevices;
4951 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004952 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4953 and doesn't really need to.*/
4954 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4955 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4956 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4957 }
Eric Laurente552edb2014-03-10 17:42:56 -07004958 return devices;
4959}
4960
François Gaffie2110e042015-03-24 08:41:51 +01004961routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4962{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004963 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004964 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004965}
4966
Eric Laurent97ac8712018-07-27 18:59:02 -07004967routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004968 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004969 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004970 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004971 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004972 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004973 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004974 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004975 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004976 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004977}
4978
Eric Laurente0720872014-03-11 09:30:41 -07004979void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004980 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004981 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004982 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4983 updateDevicesAndOutputs();
4984 break;
4985 default:
4986 break;
4987 }
4988}
4989
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004990uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004991
4992 // skip beacon mute management if a dedicated TTS output is available
4993 if (mTtsOutputAvailable) {
4994 return 0;
4995 }
4996
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004997 switch(event) {
4998 case STARTING_OUTPUT:
4999 mBeaconMuteRefCount++;
5000 break;
5001 case STOPPING_OUTPUT:
5002 if (mBeaconMuteRefCount > 0) {
5003 mBeaconMuteRefCount--;
5004 }
5005 break;
5006 case STARTING_BEACON:
5007 mBeaconPlayingRefCount++;
5008 break;
5009 case STOPPING_BEACON:
5010 if (mBeaconPlayingRefCount > 0) {
5011 mBeaconPlayingRefCount--;
5012 }
5013 break;
5014 }
5015
5016 if (mBeaconMuteRefCount > 0) {
5017 // any playback causes beacon to be muted
5018 return setBeaconMute(true);
5019 } else {
5020 // no other playback: unmute when beacon starts playing, mute when it stops
5021 return setBeaconMute(mBeaconPlayingRefCount == 0);
5022 }
5023}
5024
5025uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5026 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5027 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5028 // keep track of muted state to avoid repeating mute/unmute operations
5029 if (mBeaconMuted != mute) {
5030 // mute/unmute AUDIO_STREAM_TTS on all outputs
5031 ALOGV("\t muting %d", mute);
5032 uint32_t maxLatency = 0;
5033 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005034 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005035 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005036 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005037 0 /*delay*/, AUDIO_DEVICE_NONE);
5038 const uint32_t latency = desc->latency() * 2;
5039 if (latency > maxLatency) {
5040 maxLatency = latency;
5041 }
5042 }
5043 mBeaconMuted = mute;
5044 return maxLatency;
5045 }
5046 return 0;
5047}
5048
Eric Laurente0720872014-03-11 09:30:41 -07005049audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005050 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005051{
Eric Laurent97ac8712018-07-27 18:59:02 -07005052 // Honor explicit routing requests only if all active clients have a preferred route in which
5053 // case the last active client route is used
5054 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5055 if (deviceDesc != nullptr) {
5056 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005057 }
5058
Eric Laurente552edb2014-03-10 17:42:56 -07005059 if (fromCache) {
5060 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5061 strategy, mDeviceForStrategy[strategy]);
5062 return mDeviceForStrategy[strategy];
5063 }
François Gaffie2110e042015-03-24 08:41:51 +01005064 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005065}
5066
Eric Laurente0720872014-03-11 09:30:41 -07005067void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005068{
5069 for (int i = 0; i < NUM_STRATEGIES; i++) {
5070 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5071 }
5072 mPreviousOutputs = mOutputs;
5073}
5074
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005075uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005076 audio_devices_t prevDevice,
5077 uint32_t delayMs)
5078{
5079 // mute/unmute strategies using an incompatible device combination
5080 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5081 // if unmuting, unmute only after the specified delay
5082 if (outputDesc->isDuplicated()) {
5083 return 0;
5084 }
5085
5086 uint32_t muteWaitMs = 0;
5087 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005088 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005089
5090 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5091 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005092 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005093 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5094 bool doMute = false;
5095
5096 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5097 doMute = true;
5098 outputDesc->mStrategyMutedByDevice[i] = true;
5099 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5100 doMute = true;
5101 outputDesc->mStrategyMutedByDevice[i] = false;
5102 }
Eric Laurent99401132014-05-07 19:48:15 -07005103 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005104 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005105 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005106 // skip output if it does not share any device with current output
5107 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5108 == AUDIO_DEVICE_NONE) {
5109 continue;
5110 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005111 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 mute ? "muting" : "unmuting", i, curDevice);
5113 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005114 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005115 if (mute) {
5116 // FIXME: should not need to double latency if volume could be applied
5117 // immediately by the audioflinger mixer. We must account for the delay
5118 // between now and the next time the audioflinger thread for this output
5119 // will process a buffer (which corresponds to one buffer size,
5120 // usually 1/2 or 1/4 of the latency).
5121 if (muteWaitMs < desc->latency() * 2) {
5122 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005123 }
5124 }
5125 }
5126 }
5127 }
5128 }
5129
Eric Laurent99401132014-05-07 19:48:15 -07005130 // temporary mute output if device selection changes to avoid volume bursts due to
5131 // different per device volumes
5132 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005133 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5134 // temporary mute duration is conservatively set to 4 times the reported latency
5135 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5136 if (muteWaitMs < tempMuteWaitMs) {
5137 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005138 }
Eric Laurentdc462862016-07-19 12:29:53 -07005139
Eric Laurent99401132014-05-07 19:48:15 -07005140 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005141 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005142 // make sure that we do not start the temporary mute period too early in case of
5143 // delayed device change
5144 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005145 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005146 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005147 }
5148 }
5149 }
5150
Eric Laurente552edb2014-03-10 17:42:56 -07005151 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5152 if (muteWaitMs > delayMs) {
5153 muteWaitMs -= delayMs;
5154 usleep(muteWaitMs * 1000);
5155 return muteWaitMs;
5156 }
5157 return 0;
5158}
5159
Eric Laurentc75307b2015-03-17 15:29:32 -07005160uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005161 audio_devices_t device,
5162 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005164 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005165 const char *address,
5166 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005169 AudioParameter param;
5170 uint32_t muteWaitMs;
5171
5172 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005173 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5174 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5175 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5176 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005177 return muteWaitMs;
5178 }
5179 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5180 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005182 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005183 return 0;
5184 }
5185
5186 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005187 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005188
5189 audio_devices_t prevDevice = outputDesc->mDevice;
5190
Paul McLeanaa981192015-03-21 09:55:15 -07005191 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005192
5193 if (device != AUDIO_DEVICE_NONE) {
5194 outputDesc->mDevice = device;
5195 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005196
5197 // if the outputs are not materially active, there is no need to mute.
5198 if (requiresMuteCheck) {
5199 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5200 } else {
5201 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5202 muteWaitMs = 0;
5203 }
Eric Laurente552edb2014-03-10 17:42:56 -07005204
5205 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005206 // the requested device is AUDIO_DEVICE_NONE
5207 // OR the requested device is the same as current device
5208 // AND force is not specified
5209 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005210 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005211 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5212 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005213 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005214 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005215 return muteWaitMs;
5216 }
5217
5218 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005219
Eric Laurente552edb2014-03-10 17:42:56 -07005220 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005221 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005222 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005223 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005224 DeviceVector deviceList;
5225 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005226 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005227 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005228 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5229 device, String8(address));
5230 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005231 }
5232
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005234 PatchBuilder patchBuilder;
5235 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005237 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005238 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005239 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005240 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005241
5242 // inform all input as well
5243 for (size_t i = 0; i < mInputs.size(); i++) {
5244 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005245 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005246 AudioParameter inputCmd = AudioParameter();
5247 ALOGV("%s: inform input %d of device:%d", __func__,
5248 inputDescriptor->mIoHandle, device);
5249 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5250 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5251 inputCmd.toString(),
5252 delayMs);
5253 }
5254 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005255 }
Eric Laurente552edb2014-03-10 17:42:56 -07005256
5257 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005258 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005259
5260 return muteWaitMs;
5261}
5262
Eric Laurentc75307b2015-03-17 15:29:32 -07005263status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 int delayMs,
5265 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005266{
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 ssize_t index;
5268 if (patchHandle) {
5269 index = mAudioPatches.indexOfKey(*patchHandle);
5270 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005271 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 }
5273 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005274 return INVALID_OPERATION;
5275 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5277 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005278 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005279 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 removeAudioPatch(patchDesc->mHandle);
5281 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005282 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005283 return status;
5284}
5285
5286status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5287 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 bool force,
5289 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005290{
5291 status_t status = NO_ERROR;
5292
Eric Laurent1f2f2232014-06-02 12:01:23 -07005293 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5295 inputDesc->mDevice = device;
5296
Mikhail Naganov708e0382018-05-30 09:53:04 -07005297 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005298 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005299 PatchBuilder patchBuilder;
5300 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005301 // AUDIO_SOURCE_HOTWORD is for internal use only:
5302 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005303 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5304 auto result = usecase;
5305 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5306 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5307 }
5308 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005310 addSource(deviceList.itemAt(0));
5311 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005312 }
5313 }
5314 return status;
5315}
5316
Eric Laurent6a94d692014-05-20 11:18:06 -07005317status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5318 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005319{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005320 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 ssize_t index;
5322 if (patchHandle) {
5323 index = mAudioPatches.indexOfKey(*patchHandle);
5324 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005325 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 }
5327 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005328 return INVALID_OPERATION;
5329 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5331 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005333 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 removeAudioPatch(patchDesc->mHandle);
5335 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005336 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005337 return status;
5338}
5339
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005340sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005341 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005342 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005343 audio_format_t& format,
5344 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005345 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005346{
5347 // Choose an input profile based on the requested capture parameters: select the first available
5348 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005349 //
5350 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5351 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005352
Glenn Kasten730b9262018-03-29 15:01:26 -07005353 sp<IOProfile> firstInexact;
5354 uint32_t updatedSamplingRate = 0;
5355 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5356 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005357 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005358 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005359 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005360 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005361 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005362 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005363 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005364 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005365 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005366 &channelMask /*updatedChannelMask*/,
5367 // FIXME ugly cast
5368 (audio_output_flags_t) flags,
5369 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005370 return profile;
5371 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005372 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5373 samplingRate,
5374 &updatedSamplingRate,
5375 format,
5376 &updatedFormat,
5377 channelMask,
5378 &updatedChannelMask,
5379 // FIXME ugly cast
5380 (audio_output_flags_t) flags,
5381 false /*exactMatchRequiredForInputFlags*/)) {
5382 firstInexact = profile;
5383 }
5384
Eric Laurente552edb2014-03-10 17:42:56 -07005385 }
5386 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005387 if (firstInexact != nullptr) {
5388 samplingRate = updatedSamplingRate;
5389 format = updatedFormat;
5390 channelMask = updatedChannelMask;
5391 return firstInexact;
5392 }
Eric Laurente552edb2014-03-10 17:42:56 -07005393 return NULL;
5394}
5395
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005396
5397audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005398 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005399{
Eric Laurent97ac8712018-07-27 18:59:02 -07005400 // Honor explicit routing requests only if all active clients have a preferred route in which
5401 // case the last active client route is used
5402 sp<DeviceDescriptor> deviceDesc =
5403 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5404 if (deviceDesc != nullptr) {
5405 return deviceDesc->type();
5406 }
5407
5408
François Gaffie036e1e92015-03-19 10:16:24 +01005409 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5410 audio_devices_t selectedDeviceFromMix =
5411 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005412
François Gaffie036e1e92015-03-19 10:16:24 +01005413 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5414 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005415 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005416 return getDeviceForInputSource(inputSource);
5417}
5418
5419audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5420{
Eric Laurent97ac8712018-07-27 18:59:02 -07005421 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005422}
5423
Eric Laurente0720872014-03-11 09:30:41 -07005424float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005425 int index,
5426 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005427{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005428 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005429
5430 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5431 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5432 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5433 // the ringtone volume
5434 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5435 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5436 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5437 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5438 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5439 }
5440
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005441 // in-call: always cap volume by voice volume + some low headroom
5442 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005443 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005444 switch (stream) {
5445 case AUDIO_STREAM_SYSTEM:
5446 case AUDIO_STREAM_RING:
5447 case AUDIO_STREAM_MUSIC:
5448 case AUDIO_STREAM_ALARM:
5449 case AUDIO_STREAM_NOTIFICATION:
5450 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5451 case AUDIO_STREAM_DTMF:
5452 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005453 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005454 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005455 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005456 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005457 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005458 if (volumeDB > maxVoiceVolDb) {
5459 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5460 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5461 volumeDB = maxVoiceVolDb;
5462 }
5463 } break;
5464 default:
5465 break;
5466 }
5467 }
5468
Eric Laurente552edb2014-03-10 17:42:56 -07005469 // if a headset is connected, apply the following rules to ring tones and notifications
5470 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005471 // - always attenuate notifications volume by 6dB
5472 // - attenuate ring tones volume by 6dB unless music is not playing and
5473 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005474 // - if music is playing, always limit the volume to current music volume,
5475 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005476 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005477 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5478 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5479 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005480 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005481 AUDIO_DEVICE_OUT_USB_HEADSET |
5482 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005483 ((stream_strategy == STRATEGY_SONIFICATION)
5484 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005485 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005486 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005487 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005488 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005489 // when the phone is ringing we must consider that music could have been paused just before
5490 // by the music application and behave as if music was active if the last music track was
5491 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005492 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005493 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005494 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005495 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005496 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005497 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5498 musicDevice),
5499 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005500 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5501 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005502 if (volumeDB > minVolDB) {
5503 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005504 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005505 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005506 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5507 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5508 // on A2DP, also ensure notification volume is not too low compared to media when
5509 // intended to be played
5510 if ((volumeDB > -96.0f) &&
5511 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5512 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5513 stream, device,
5514 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5515 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5516 }
5517 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005518 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5519 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005520 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005521 }
5522 }
5523
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005524 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005525}
5526
Eric Laurent3839bc02018-07-10 18:33:34 -07005527int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5528 audio_stream_type_t srcStream,
5529 audio_stream_type_t dstStream)
5530{
5531 if (srcStream == dstStream) {
5532 return srcIndex;
5533 }
5534 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5535 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5536 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5537 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5538
5539 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5540}
5541
Eric Laurente0720872014-03-11 09:30:41 -07005542status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005543 int index,
5544 const sp<AudioOutputDescriptor>& outputDesc,
5545 audio_devices_t device,
5546 int delayMs,
5547 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005548{
Eric Laurente552edb2014-03-10 17:42:56 -07005549 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005550 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005551 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005552 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005553 return NO_ERROR;
5554 }
François Gaffie2110e042015-03-24 08:41:51 +01005555 audio_policy_forced_cfg_t forceUseForComm =
5556 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005557 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005558 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5559 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005560 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005561 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005562 return INVALID_OPERATION;
5563 }
5564
Eric Laurentc75307b2015-03-17 15:29:32 -07005565 if (device == AUDIO_DEVICE_NONE) {
5566 device = outputDesc->device();
5567 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005568
Eric Laurentffbc80f2015-03-18 18:30:19 -07005569 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005570 if (outputDesc->isFixedVolume(device) ||
5571 // Force VoIP volume to max for bluetooth SCO
5572 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5573 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005574 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005575 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005576
Eric Laurentffbc80f2015-03-18 18:30:19 -07005577 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005578
Eric Laurent3b73df72014-03-11 09:06:29 -07005579 if (stream == AUDIO_STREAM_VOICE_CALL ||
5580 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005581 float voiceVolume;
5582 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005583 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005584 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005585 } else {
5586 voiceVolume = 1.0;
5587 }
5588
Eric Laurent18fba842016-03-31 14:41:26 -07005589 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005590 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5591 mLastVoiceVolume = voiceVolume;
5592 }
5593 }
5594
5595 return NO_ERROR;
5596}
5597
Eric Laurentc75307b2015-03-17 15:29:32 -07005598void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5599 audio_devices_t device,
5600 int delayMs,
5601 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005602{
Eric Laurentc75307b2015-03-17 15:29:32 -07005603 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005604
Eric Laurent794fde22016-03-11 09:50:45 -08005605 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005606 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005607 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005608 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005609 device,
5610 delayMs,
5611 force);
5612 }
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 bool on,
5617 const sp<AudioOutputDescriptor>& outputDesc,
5618 int delayMs,
5619 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005620{
Eric Laurent72249d52015-06-08 11:12:15 -07005621 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5622 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005623 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005624 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005626 }
5627 }
5628}
5629
Eric Laurente0720872014-03-11 09:30:41 -07005630void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005631 bool on,
5632 const sp<AudioOutputDescriptor>& outputDesc,
5633 int delayMs,
5634 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005635{
Eric Laurente552edb2014-03-10 17:42:56 -07005636 if (device == AUDIO_DEVICE_NONE) {
5637 device = outputDesc->device();
5638 }
5639
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5641 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005642
5643 if (on) {
5644 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005645 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005646 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005647 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005648 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005649 }
5650 }
5651 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5652 outputDesc->mMuteCount[stream]++;
5653 } else {
5654 if (outputDesc->mMuteCount[stream] == 0) {
5655 ALOGV("setStreamMute() unmuting non muted stream!");
5656 return;
5657 }
5658 if (--outputDesc->mMuteCount[stream] == 0) {
5659 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005660 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005661 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005662 device,
5663 delayMs);
5664 }
5665 }
5666}
5667
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005668audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5669{
5670 // flags to stream type mapping
5671 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5672 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5673 }
5674 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5675 return AUDIO_STREAM_BLUETOOTH_SCO;
5676 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005677 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5678 return AUDIO_STREAM_TTS;
5679 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005680
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005681 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005682}
Eric Laurente83b55d2014-11-14 10:06:21 -08005683
François Gaffie53615e22015-03-19 09:24:12 +01005684bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5685{
Eric Laurente83b55d2014-11-14 10:06:21 -08005686 // has flags that map to a strategy?
5687 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5688 return true;
5689 }
5690
5691 // has known usage?
5692 switch (paa->usage) {
5693 case AUDIO_USAGE_UNKNOWN:
5694 case AUDIO_USAGE_MEDIA:
5695 case AUDIO_USAGE_VOICE_COMMUNICATION:
5696 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5697 case AUDIO_USAGE_ALARM:
5698 case AUDIO_USAGE_NOTIFICATION:
5699 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5700 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5701 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5702 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5703 case AUDIO_USAGE_NOTIFICATION_EVENT:
5704 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5705 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5706 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5707 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005708 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005709 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005710 break;
5711 default:
5712 return false;
5713 }
5714 return true;
5715}
5716
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005717bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005718 routing_strategy strategy, uint32_t inPastMs,
5719 nsecs_t sysTime) const
5720{
5721 if ((sysTime == 0) && (inPastMs != 0)) {
5722 sysTime = systemTime();
5723 }
Eric Laurent794fde22016-03-11 09:50:45 -08005724 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005725 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005726 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005727 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5728 return true;
5729 }
5730 }
5731 return false;
5732}
5733
Eric Laurent484e9272018-06-07 17:29:23 -07005734bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5735 routing_strategy strategy, uint32_t inPastMs,
5736 nsecs_t sysTime) const
5737{
5738 for (size_t i = 0; i < mOutputs.size(); i++) {
5739 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5740 if (outputDesc->sharesHwModuleWith(desc)
5741 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5742 return true;
5743 }
5744 }
5745 return false;
5746}
5747
François Gaffie2110e042015-03-24 08:41:51 +01005748audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5749{
5750 return mEngine->getForceUse(usage);
5751}
5752
5753bool AudioPolicyManager::isInCall()
5754{
5755 return isStateInCall(mEngine->getPhoneState());
5756}
5757
5758bool AudioPolicyManager::isStateInCall(int state)
5759{
5760 return is_state_in_call(state);
5761}
5762
Eric Laurentd60560a2015-04-10 11:31:20 -07005763void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5764{
5765 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005766 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5767 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5768 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5769 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005770 }
5771 }
5772
5773 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5774 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5775 bool release = false;
5776 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5777 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5778 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5779 source->ext.device.type == deviceDesc->type()) {
5780 release = true;
5781 }
5782 }
5783 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5784 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5785 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5786 sink->ext.device.type == deviceDesc->type()) {
5787 release = true;
5788 }
5789 }
5790 if (release) {
5791 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5792 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5793 }
5794 }
5795}
5796
Phil Burk09bc4612016-02-24 15:58:15 -08005797// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005798void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5799 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005800 // TODO Set this based on Config properties.
5801 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005802
5803 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5804 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005805 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005806
jiabin81772902018-04-02 17:52:27 -07005807 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5808 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5809 formats.clear();
5810 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5811 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005812 }
jiabin81772902018-04-02 17:52:27 -07005813 // Always enable IEC61937 when in MANUAL mode.
5814 formats.add(AUDIO_FORMAT_IEC61937);
5815 } else { // NEVER, AUTO or ALWAYS
5816 // Analyze original support for various formats.
5817 bool supportsAC3 = false;
5818 bool supportsOtherSurround = false;
5819 bool supportsIEC61937 = false;
5820 mSurroundFormats.clear();
5821 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5822 audio_format_t format = formats[formatIndex];
5823 switch (format) {
5824 case AUDIO_FORMAT_AC3:
5825 supportsAC3 = true;
5826 break;
5827 case AUDIO_FORMAT_E_AC3:
5828 case AUDIO_FORMAT_DTS:
5829 case AUDIO_FORMAT_DTS_HD:
5830 // If ALWAYS, remove all other surround formats here
5831 // since we will add them later.
5832 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5833 formats.removeAt(formatIndex);
5834 formatIndex--;
5835 }
5836 supportsOtherSurround = true;
5837 break;
5838 case AUDIO_FORMAT_IEC61937:
5839 supportsIEC61937 = true;
5840 break;
5841 default:
5842 break;
5843 }
5844 }
Phil Burk09bc4612016-02-24 15:58:15 -08005845
jiabin81772902018-04-02 17:52:27 -07005846 // Modify formats based on surround preferences.
5847 // If NEVER, remove support for surround formats.
5848 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5849 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5850 // Remove surround sound related formats.
5851 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5852 audio_format_t format = formats[formatIndex];
5853 switch(format) {
5854 case AUDIO_FORMAT_AC3:
5855 case AUDIO_FORMAT_E_AC3:
5856 case AUDIO_FORMAT_DTS:
5857 case AUDIO_FORMAT_DTS_HD:
5858 case AUDIO_FORMAT_IEC61937:
5859 formats.removeAt(formatIndex);
5860 break;
5861 default:
5862 formatIndex++; // keep it
5863 break;
5864 }
5865 }
5866 supportsAC3 = false;
5867 supportsOtherSurround = false;
5868 supportsIEC61937 = false;
5869 }
5870 } else { // AUTO or ALWAYS
5871 // Most TVs support AC3 even if they do not report it in the EDID.
5872 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5873 && !supportsAC3) {
5874 formats.add(AUDIO_FORMAT_AC3);
5875 supportsAC3 = true;
5876 }
5877
5878 // If ALWAYS, add support for raw surround formats if all are missing.
5879 // This assumes that if any of these formats are reported by the HAL
5880 // then the report is valid and should not be modified.
5881 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5882 formats.add(AUDIO_FORMAT_E_AC3);
5883 formats.add(AUDIO_FORMAT_DTS);
5884 formats.add(AUDIO_FORMAT_DTS_HD);
5885 supportsOtherSurround = true;
5886 }
5887
5888 // Add support for IEC61937 if any raw surround supported.
5889 // The HAL could do this but add it here, just in case.
5890 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5891 formats.add(AUDIO_FORMAT_IEC61937);
5892 supportsIEC61937 = true;
5893 }
5894
5895 // Add reported surround sound formats to enabled surround formats.
5896 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005897 audio_format_t format = formats[formatIndex];
Mikhail Naganov02743e22018-11-28 15:56:55 -08005898 if (mConfig.getSurroundFormats().count(format) != 0) {
5899 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005900 }
Phil Burk09bc4612016-02-24 15:58:15 -08005901 }
Phil Burk07ac1142016-03-25 13:39:29 -07005902 }
Phil Burk09bc4612016-02-24 15:58:15 -08005903 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005904}
5905
5906// Modify the list of channel masks supported.
5907void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5908 ChannelsVector &channelMasks = *channelMasksPtr;
5909 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5910 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5911
5912 // If NEVER, then remove support for channelMasks > stereo.
5913 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5914 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5915 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5916 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5917 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5918 channelMasks.removeAt(maskIndex);
5919 } else {
5920 maskIndex++;
5921 }
5922 }
jiabin81772902018-04-02 17:52:27 -07005923 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5924 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5925 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005926 bool supports5dot1 = false;
5927 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005928 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005929 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5930 supports5dot1 = true;
5931 break;
5932 }
5933 }
5934 // If not then add 5.1 support.
5935 if (!supports5dot1) {
5936 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5937 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5938 }
Phil Burk09bc4612016-02-24 15:58:15 -08005939 }
5940}
5941
Phil Burk00eeb322016-03-31 12:41:00 -07005942void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5943 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005944 AudioProfileVector &profiles)
5945{
5946 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005947
François Gaffie112b0af2015-11-19 16:13:25 +01005948 // Format MUST be checked first to update the list of AudioProfile
5949 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005950 reply = mpClientInterface->getParameters(
5951 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005952 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005953 AudioParameter repliedParameters(reply);
5954 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005955 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005956 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5957 return;
5958 }
Phil Burk09bc4612016-02-24 15:58:15 -08005959 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005960 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005961 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005962 }
Phil Burk09bc4612016-02-24 15:58:15 -08005963 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005964 }
François Gaffie112b0af2015-11-19 16:13:25 +01005965
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005966 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005967 ChannelsVector channelMasks;
5968 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005969 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005970 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005971
5972 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005973 reply = mpClientInterface->getParameters(
5974 ioHandle,
5975 requestedParameters.toString() + ";" +
5976 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005977 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005978 AudioParameter repliedParameters(reply);
5979 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005980 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005981 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005982 }
5983 }
5984 if (profiles.hasDynamicChannelsFor(format)) {
5985 reply = mpClientInterface->getParameters(ioHandle,
5986 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005987 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005988 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005989 AudioParameter repliedParameters(reply);
5990 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005991 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005992 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005993 if (device == AUDIO_DEVICE_OUT_HDMI) {
5994 filterSurroundChannelMasks(&channelMasks);
5995 }
François Gaffie112b0af2015-11-19 16:13:25 +01005996 }
5997 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005998 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005999 }
6000}
Eric Laurentd60560a2015-04-10 11:31:20 -07006001
Mikhail Naganovdc769682018-05-04 15:34:08 -07006002status_t AudioPolicyManager::installPatch(const char *caller,
6003 audio_patch_handle_t *patchHandle,
6004 AudioIODescriptorInterface *ioDescriptor,
6005 const struct audio_patch *patch,
6006 int delayMs)
6007{
6008 ssize_t index = mAudioPatches.indexOfKey(
6009 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6010 *patchHandle : ioDescriptor->getPatchHandle());
6011 sp<AudioPatch> patchDesc;
6012 status_t status = installPatch(
6013 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6014 if (status == NO_ERROR) {
6015 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6016 }
6017 return status;
6018}
6019
6020status_t AudioPolicyManager::installPatch(const char *caller,
6021 ssize_t index,
6022 audio_patch_handle_t *patchHandle,
6023 const struct audio_patch *patch,
6024 int delayMs,
6025 uid_t uid,
6026 sp<AudioPatch> *patchDescPtr)
6027{
6028 sp<AudioPatch> patchDesc;
6029 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6030 if (index >= 0) {
6031 patchDesc = mAudioPatches.valueAt(index);
6032 afPatchHandle = patchDesc->mAfPatchHandle;
6033 }
6034
6035 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6036 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6037 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6038 if (status == NO_ERROR) {
6039 if (index < 0) {
6040 patchDesc = new AudioPatch(patch, uid);
6041 addAudioPatch(patchDesc->mHandle, patchDesc);
6042 } else {
6043 patchDesc->mPatch = *patch;
6044 }
6045 patchDesc->mAfPatchHandle = afPatchHandle;
6046 if (patchHandle) {
6047 *patchHandle = patchDesc->mHandle;
6048 }
6049 nextAudioPortGeneration();
6050 mpClientInterface->onAudioPatchListUpdate();
6051 }
6052 if (patchDescPtr) *patchDescPtr = patchDesc;
6053 return status;
6054}
6055
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006056} // namespace android