blob: 52980344cf820e54512dd25e754c49d474f519ea [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010029
Eric Laurentd4692962014-05-05 18:13:44 -070030#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070031#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070032
François Gaffie2110e042015-03-24 08:41:51 +010033#include <AudioPolicyManagerInterface.h>
34#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070037#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080038#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070039#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070040#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070041#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010043#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010044#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010045#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010046#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010048#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010049#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurentdc462862016-07-19 12:29:53 -070053//FIXME: workaround for truncated touch sounds
54// to be removed when the problem is handled by system UI
55#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070056
57// Largest difference in dB on earpiece in call between the voice volume and another
58// media / notification / system volume.
59constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
60
Eric Laurente552edb2014-03-10 17:42:56 -070061// ----------------------------------------------------------------------------
62// AudioPolicyInterface implementation
63// ----------------------------------------------------------------------------
64
Eric Laurente0720872014-03-11 09:30:41 -070065status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080066 audio_policy_dev_state_t state,
67 const char *device_address,
68 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070069{
Paul McLeane743a472015-01-28 11:07:31 -080070 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080071}
72
François Gaffie44481e72016-04-20 07:49:57 +020073void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
74 audio_policy_dev_state_t state,
75 const String8 &device_address)
76{
77 AudioParameter param(device_address);
78 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070079 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020080 param.addInt(key, device);
81 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
82}
83
Eric Laurentc73ca6e2014-12-12 14:34:22 -080084status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080085 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080086 const char *device_address,
87 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080088{
Paul McLeane743a472015-01-28 11:07:31 -080089 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -080090 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070091
92 // connect/disconnect only 1 device at a time
93 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
94
François Gaffie53615e22015-03-19 09:24:12 +010095 sp<DeviceDescriptor> devDesc =
96 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080097
Eric Laurente552edb2014-03-10 17:42:56 -070098 // handle output devices
99 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700100 SortedVector <audio_io_handle_t> outputs;
101
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
103
Eric Laurente552edb2014-03-10 17:42:56 -0700104 // save a copy of the opened output descriptors before any output is opened or closed
105 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
106 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700107 switch (state)
108 {
109 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800110 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700111 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700112 ALOGW("setDeviceConnectionState() device already connected: %x", device);
113 return INVALID_OPERATION;
114 }
115 ALOGV("setDeviceConnectionState() connecting device %x", device);
116
Eric Laurente552edb2014-03-10 17:42:56 -0700117 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700118 index = mAvailableOutputDevices.add(devDesc);
119 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100120 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700121 if (module == 0) {
122 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
123 device);
124 mAvailableOutputDevices.remove(devDesc);
125 return INVALID_OPERATION;
126 }
Paul McLeane743a472015-01-28 11:07:31 -0800127 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 } else {
129 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700130 }
131
François Gaffie44481e72016-04-20 07:49:57 +0200132 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
133 // parameters on newly connected devices (instead of opening the outputs...)
134 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
135
Eric Laurenta1d525f2015-01-29 13:36:45 -0800136 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700137 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200138
139 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
140 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700141 return INVALID_OPERATION;
142 }
François Gaffie2110e042015-03-24 08:41:51 +0100143 // Propagate device availability to Engine
144 mEngine->setDeviceConnectionState(devDesc, state);
145
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700146 // outputs should never be empty here
147 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
148 "checkOutputsForDevice() returned no outputs but status OK");
149 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
150 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800151
Eric Laurent3ae5f312015-02-03 17:12:08 -0800152 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700153 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700154 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700155 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700156 ALOGW("setDeviceConnectionState() device not connected: %x", device);
157 return INVALID_OPERATION;
158 }
159
Paul McLean5c477aa2014-08-20 16:47:57 -0700160 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
161
Paul McLeane743a472015-01-28 11:07:31 -0800162 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200163 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700164
Eric Laurente552edb2014-03-10 17:42:56 -0700165 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700167
Eric Laurenta1d525f2015-01-29 13:36:45 -0800168 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100169
170 // Propagate device availability to Engine
171 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700172 } break;
173
174 default:
175 ALOGE("setDeviceConnectionState() invalid state: %x", state);
176 return BAD_VALUE;
177 }
178
Eric Laurent3a4311c2014-03-17 12:00:47 -0700179 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
180 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700181 checkA2dpSuspend();
182 checkOutputForAllStrategies();
183 // outputs must be closed after checkOutputForAllStrategies() is executed
184 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800185 for (audio_io_handle_t output : outputs) {
186 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // close unused outputs after device disconnection or direct outputs that have been
188 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700189 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700190 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
191 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800192 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700193 }
194 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 // check again after closing A2DP output to reset mA2dpSuspended if needed
196 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700197 }
198
199 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700200 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700201 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
202 updateCallRouting(newDevice);
203 }
Eric Laurente552edb2014-03-10 17:42:56 -0700204 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
206 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
207 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700208 // do not force device change on duplicated output because if device is 0, it will
209 // also force a device 0 for the two outputs it is duplicated to which may override
210 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700211 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100212 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700213 // always force when disconnecting (a non-duplicated device)
214 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700215 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700216 }
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218
Eric Laurentd60560a2015-04-10 11:31:20 -0700219 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
220 cleanUpForDevice(devDesc);
221 }
222
Eric Laurent72aa32f2014-05-30 18:51:48 -0700223 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700224 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700225 } // end if is output device
226
Eric Laurente552edb2014-03-10 17:42:56 -0700227 // handle input devices
228 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700229 SortedVector <audio_io_handle_t> inputs;
230
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700232 switch (state)
233 {
234 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700235 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700237 ALOGW("setDeviceConnectionState() device already connected: %d", device);
238 return INVALID_OPERATION;
239 }
François Gaffie53615e22015-03-19 09:24:12 +0100240 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700241 if (module == NULL) {
242 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
243 device);
244 return INVALID_OPERATION;
245 }
François Gaffie44481e72016-04-20 07:49:57 +0200246
247 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
248 // parameters on newly connected devices (instead of opening the inputs...)
249 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
250
Paul McLean9080a4c2015-06-18 08:24:02 -0700251 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200252 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
253 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700254 return INVALID_OPERATION;
255 }
256
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 index = mAvailableInputDevices.add(devDesc);
258 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800259 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 } else {
261 return NO_MEMORY;
262 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800263
François Gaffie2110e042015-03-24 08:41:51 +0100264 // Propagate device availability to Engine
265 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700266 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700267
268 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700269 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700270 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700271 ALOGW("setDeviceConnectionState() device not connected: %d", device);
272 return INVALID_OPERATION;
273 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700274
275 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
276
277 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200278 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700279
Paul McLean9080a4c2015-06-18 08:24:02 -0700280 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700282
François Gaffie2110e042015-03-24 08:41:51 +0100283 // Propagate device availability to Engine
284 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 default:
288 ALOGE("setDeviceConnectionState() invalid state: %x", state);
289 return BAD_VALUE;
290 }
291
Eric Laurentd4692962014-05-05 18:13:44 -0700292 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700293 // As the input device list can impact the output device selection, update
294 // getDeviceForStrategy() cache
295 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700296
Eric Laurent87ffa392015-05-22 10:32:38 -0700297 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700298 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
299 updateCallRouting(newDevice);
300 }
301
Eric Laurentd60560a2015-04-10 11:31:20 -0700302 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
303 cleanUpForDevice(devDesc);
304 }
305
Eric Laurentb52c1522014-05-20 11:27:36 -0700306 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700307 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700308 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700309
310 ALOGW("setDeviceConnectionState() invalid device: %x", device);
311 return BAD_VALUE;
312}
313
Eric Laurente0720872014-03-11 09:30:41 -0700314audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100315 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700316{
Eric Laurent634b7142016-04-20 13:48:02 -0700317 sp<DeviceDescriptor> devDesc =
318 mHwModules.getDeviceDescriptor(device, device_address, "",
319 (strlen(device_address) != 0)/*matchAddress*/);
320
321 if (devDesc == 0) {
322 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
323 device, device_address);
324 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
325 }
François Gaffie53615e22015-03-19 09:24:12 +0100326
Eric Laurent3a4311c2014-03-17 12:00:47 -0700327 DeviceVector *deviceVector;
328
Eric Laurente552edb2014-03-10 17:42:56 -0700329 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700330 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700331 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700332 deviceVector = &mAvailableInputDevices;
333 } else {
334 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
335 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700336 }
Eric Laurent634b7142016-04-20 13:48:02 -0700337
338 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
339 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800340}
341
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800342status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
343 const char *device_address,
344 const char *device_name)
345{
346 status_t status;
347
348 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
349 device, device_address, device_name);
350
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800351 // connect/disconnect only 1 device at a time
352 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
353
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800354 // Check if the device is currently connected
355 sp<DeviceDescriptor> devDesc =
356 mHwModules.getDeviceDescriptor(device, device_address, device_name);
357 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
358 if (index < 0) {
359 // Nothing to do: device is not connected
360 return NO_ERROR;
361 }
362
363 // Toggle the device state: UNAVAILABLE -> AVAILABLE
364 // This will force reading again the device configuration
365 status = setDeviceConnectionState(device,
366 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
367 device_address, device_name);
368 if (status != NO_ERROR) {
369 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
370 status);
371 return status;
372 }
373
374 status = setDeviceConnectionState(device,
375 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
376 device_address, device_name);
377 if (status != NO_ERROR) {
378 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
379 status);
380 return status;
381 }
382
383 return NO_ERROR;
384}
385
Eric Laurentdc462862016-07-19 12:29:53 -0700386uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700387{
388 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700389 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700390
Andy Hunga76c7de2016-12-13 19:14:31 -0800391 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700392 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700393 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800394 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700395 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
396
397 // release existing RX patch if any
398 if (mCallRxPatch != 0) {
399 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
400 mCallRxPatch.clear();
401 }
402 // release TX patch if any
403 if (mCallTxPatch != 0) {
404 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
405 mCallTxPatch.clear();
406 }
407
408 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
409 // via setOutputDevice() on primary output.
410 // Otherwise, create two audio patches for TX and RX path.
411 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700412 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700413 // If the TX device is also on the primary HW module, setOutputDevice() will take care
414 // of it due to legacy implementation. If not, create a patch.
415 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
416 == AUDIO_DEVICE_NONE) {
417 createTxPatch = true;
418 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700419 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800420 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700421 createTxPatch = true;
422 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700423 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800424 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
425 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700426
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800427 return muteWaitMs;
428}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800430sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
431 bool isRx, audio_devices_t device, uint32_t delayMs) {
432 struct audio_patch patch;
433 patch.num_sources = 1;
434 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800436 sp<DeviceDescriptor> txSourceDeviceDesc;
437 if (isRx) {
438 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
439 fillAudioPortConfigForDevice(
440 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
441 } else {
442 txSourceDeviceDesc = fillAudioPortConfigForDevice(
443 mAvailableInputDevices, device, &patch.sources[0]);
444 fillAudioPortConfigForDevice(
445 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
446 }
447
448 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
449 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
450 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
451 // request to reuse existing output stream if one is already opened to reach the target device
452 if (output != AUDIO_IO_HANDLE_NONE) {
453 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
454 ALOG_ASSERT(!outputDesc->isDuplicated(),
455 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
456 outputDesc->toAudioPortConfig(&patch.sources[1]);
457 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
458 patch.num_sources = 2;
459 }
460
461 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700462 // terminate active capture if on the same HW module as the call TX source device
463 // FIXME: would be better to refine to only inputs whose profile connects to the
464 // call TX device but this information is not in the audio patch and logic here must be
465 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800466 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800467 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
468 AudioSessionCollection activeSessions =
469 activeDesc->getAudioSessions(true /*activeOnly*/);
470 for (size_t j = 0; j < activeSessions.size(); j++) {
471 audio_session_t activeSession = activeSessions.keyAt(j);
472 stopInput(activeDesc->mIoHandle, activeSession);
473 releaseInput(activeDesc->mIoHandle, activeSession);
474 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700475 }
476 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477 }
Eric Laurentdc462862016-07-19 12:29:53 -0700478
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
480 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
481 ALOGW_IF(status != NO_ERROR,
482 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
483 sp<AudioPatch> audioPatch;
484 if (status == NO_ERROR) {
485 audioPatch = new AudioPatch(&patch, mUidCached);
486 audioPatch->mAfPatchHandle = afPatchHandle;
487 audioPatch->mUid = mUidCached;
488 }
489 return audioPatch;
490}
491
492sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
493 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
494 DeviceVector deviceList = devices.getDevicesFromType(device);
495 ALOG_ASSERT(!deviceList.isEmpty(),
496 "%s() selected device type %#x is not in devices list", __func__, device);
497 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
498 deviceDesc->toAudioPortConfig(config);
499 return deviceDesc;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700500}
501
Eric Laurente0720872014-03-11 09:30:41 -0700502void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700503{
504 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100505 // store previous phone state for management of sonification strategy below
506 int oldState = mEngine->getPhoneState();
507
508 if (mEngine->setPhoneState(state) != NO_ERROR) {
509 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700510 return;
511 }
François Gaffie2110e042015-03-24 08:41:51 +0100512 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700513 // if leaving call state, handle special case of active streams
514 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700515 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700516 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800517 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700518 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700519 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800520
Eric Laurent63dea1d2015-07-02 17:10:28 -0700521 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800522 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700523 }
524
François Gaffie2110e042015-03-24 08:41:51 +0100525 /**
526 * Switching to or from incall state or switching between telephony and VoIP lead to force
527 * routing command.
528 */
529 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
530 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700531
532 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700533 checkA2dpSuspend();
534 checkOutputForAllStrategies();
535 updateDevicesAndOutputs();
536
Eric Laurente552edb2014-03-10 17:42:56 -0700537 int delayMs = 0;
538 if (isStateInCall(state)) {
539 nsecs_t sysTime = systemTime();
540 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700541 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 // mute media and sonification strategies and delay device switch by the largest
543 // latency of any output where either strategy is active.
544 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100545 if ((isStrategyActive(desc, STRATEGY_MEDIA,
546 SONIFICATION_HEADSET_MUSIC_DELAY,
547 sysTime) ||
548 isStrategyActive(desc, STRATEGY_SONIFICATION,
549 SONIFICATION_HEADSET_MUSIC_DELAY,
550 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700551 (delayMs < (int)desc->latency()*2)) {
552 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700553 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700554 setStrategyMute(STRATEGY_MEDIA, true, desc);
555 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700556 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700557 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
558 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700559 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
560 }
561 }
562
Eric Laurent87ffa392015-05-22 10:32:38 -0700563 if (hasPrimaryOutput()) {
564 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
565 // the device returned is not necessarily reachable via this output
566 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
567 // force routing command to audio hardware when ending call
568 // even if no device change is needed
569 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
570 rxDevice = mPrimaryOutput->device();
571 }
Eric Laurente552edb2014-03-10 17:42:56 -0700572
Eric Laurent87ffa392015-05-22 10:32:38 -0700573 if (state == AUDIO_MODE_IN_CALL) {
574 updateCallRouting(rxDevice, delayMs);
575 } else if (oldState == AUDIO_MODE_IN_CALL) {
576 if (mCallRxPatch != 0) {
577 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
578 mCallRxPatch.clear();
579 }
580 if (mCallTxPatch != 0) {
581 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
582 mCallTxPatch.clear();
583 }
584 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
585 } else {
586 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700587 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700588 }
Eric Laurente552edb2014-03-10 17:42:56 -0700589 // if entering in call state, handle special case of active streams
590 // pertaining to sonification strategy see handleIncallSonification()
591 if (isStateInCall(state)) {
592 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800593 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700594 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700595 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700596
597 // force reevaluating accessibility routing when call starts
598 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
600
601 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700602 if (state == AUDIO_MODE_RINGTONE &&
603 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700604 mLimitRingtoneVolume = true;
605 } else {
606 mLimitRingtoneVolume = false;
607 }
608}
609
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700610audio_mode_t AudioPolicyManager::getPhoneState() {
611 return mEngine->getPhoneState();
612}
613
Eric Laurente0720872014-03-11 09:30:41 -0700614void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700615 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700616{
François Gaffie2110e042015-03-24 08:41:51 +0100617 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700618 if (config == mEngine->getForceUse(usage)) {
619 return;
620 }
Eric Laurente552edb2014-03-10 17:42:56 -0700621
François Gaffie2110e042015-03-24 08:41:51 +0100622 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
623 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
624 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700625 }
François Gaffie2110e042015-03-24 08:41:51 +0100626 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
627 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
628 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700629
630 // check for device and output changes triggered by new force usage
631 checkA2dpSuspend();
632 checkOutputForAllStrategies();
633 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800634
Eric Laurentdc462862016-07-19 12:29:53 -0700635 //FIXME: workaround for truncated touch sounds
636 // to be removed when the problem is handled by system UI
637 uint32_t delayMs = 0;
638 uint32_t waitMs = 0;
639 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
640 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
641 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700642 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700643 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700644 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700645 }
Eric Laurente552edb2014-03-10 17:42:56 -0700646 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700647 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
648 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
649 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700650 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
651 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700652 }
Eric Laurente552edb2014-03-10 17:42:56 -0700653 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700654 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700655 }
656 }
657
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800658 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800659 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700660 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800661 if (activeDesc->mProfile->getSupportedDevices().types() &
662 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
663 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700664 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800665 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
Eric Laurente552edb2014-03-10 17:42:56 -0700668}
669
Eric Laurente0720872014-03-11 09:30:41 -0700670void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700671{
672 ALOGV("setSystemProperty() property %s, value %s", property, value);
673}
674
675// Find a direct output profile compatible with the parameters passed, even if the input flags do
676// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800677sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700678 audio_devices_t device,
679 uint32_t samplingRate,
680 audio_format_t format,
681 audio_channel_mask_t channelMask,
682 audio_output_flags_t flags)
683{
Eric Laurent861a6282015-05-18 15:40:16 -0700684 // only retain flags that will drive the direct output profile selection
685 // if explicitly requested
686 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700687 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
688 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700689 flags =
690 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
691
692 sp<IOProfile> profile;
693
Mikhail Naganovd4120142017-12-06 15:49:22 -0800694 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800695 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700696 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700697 samplingRate, NULL /*updatedSamplingRate*/,
698 format, NULL /*updatedFormat*/,
699 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700700 flags)) {
701 continue;
702 }
703 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100704 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700705 continue;
706 }
707 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100708 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700709 continue;
710 }
711 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100712 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700713 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700714 }
Eric Laurente552edb2014-03-10 17:42:56 -0700715 }
716 }
Eric Laurent861a6282015-05-18 15:40:16 -0700717 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700718}
719
Eric Laurentf4e63452017-11-06 19:31:46 +0000720audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700721{
Eric Laurent3b73df72014-03-11 09:06:29 -0700722 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700723 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800724
725 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
726 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
727 // format, flags, etc. This may result in some discrepancy for functions that utilize
728 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
729 // and AudioSystem::getOutputSamplingRate().
730
Eric Laurentf4e63452017-11-06 19:31:46 +0000731 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
732 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700733
Eric Laurentf4e63452017-11-06 19:31:46 +0000734 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
735 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700736}
737
Eric Laurente83b55d2014-11-14 10:06:21 -0800738status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
739 audio_io_handle_t *output,
740 audio_session_t session,
741 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700742 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800743 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800744 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700745 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800746 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700747{
Eric Laurente83b55d2014-11-14 10:06:21 -0800748 audio_attributes_t attributes;
749 if (attr != NULL) {
750 if (!isValidAttributes(attr)) {
751 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
752 attr->usage, attr->content_type, attr->flags,
753 attr->tags);
754 return BAD_VALUE;
755 }
756 attributes = *attr;
757 } else {
758 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
759 ALOGE("getOutputForAttr(): invalid stream type");
760 return BAD_VALUE;
761 }
762 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700763 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800764
765 // TODO: check for existing client for this port ID
766 if (*portId == AUDIO_PORT_HANDLE_NONE) {
767 *portId = AudioPort::getNextUniqueId();
768 }
769
Eric Laurentc75307b2015-03-17 15:29:32 -0700770 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800771 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100772 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800773 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100774 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800775 }
François Gaffie036e1e92015-03-19 10:16:24 +0100776 *stream = streamTypefromAttributesInt(&attributes);
777 *output = desc->mIoHandle;
778 ALOGV("getOutputForAttr() returns output %d", *output);
779 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800780 }
781 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
782 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
783 return BAD_VALUE;
784 }
785
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700786 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
787 " session %d selectedDeviceId %d",
788 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700789 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700790
791 *stream = streamTypefromAttributesInt(&attributes);
792
793 // Explicit routing?
794 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700795 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800796 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700797 }
798 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700799
Eric Laurente83b55d2014-11-14 10:06:21 -0800800 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700801 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700802
Eric Laurente83b55d2014-11-14 10:06:21 -0800803 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700804 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
805 }
806
Eric Laurentfe231122017-11-17 17:48:06 -0800807 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %x, channel mask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800808 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700809
Eric Laurentfe231122017-11-17 17:48:06 -0800810 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800811 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700812 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800813 return INVALID_OPERATION;
814 }
Paul McLeanaa981192015-03-21 09:55:15 -0700815
Eric Laurent2ac76942017-06-22 17:17:09 -0700816 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
817 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
818 : AUDIO_PORT_HANDLE_NONE;
819
820 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
821
Eric Laurente83b55d2014-11-14 10:06:21 -0800822 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700823}
824
825audio_io_handle_t AudioPolicyManager::getOutputForDevice(
826 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800827 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700828 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800829 const audio_config_t *config,
830 audio_output_flags_t flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700832 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700833 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834
Eric Laurente552edb2014-03-10 17:42:56 -0700835 // open a direct output if required by specified parameters
836 //force direct flag if offload flag is set: offloading implies a direct output stream
837 // and all common behaviors are driven by checking only the direct flag
838 // this should normally be set appropriately in the policy configuration file
839 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700840 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700842 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
843 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
844 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 // only allow deep buffering for music stream type
846 if (stream != AUDIO_STREAM_MUSIC) {
847 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700848 } else if (/* stream == AUDIO_STREAM_MUSIC && */
849 flags == AUDIO_OUTPUT_FLAG_NONE &&
850 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
851 // use DEEP_BUFFER as default output for music stream type
852 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800853 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700854 if (stream == AUDIO_STREAM_TTS) {
855 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700856 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800857 audio_is_linear_pcm(config->format)) {
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700858 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
859 AUDIO_OUTPUT_FLAG_DIRECT);
860 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700861 }
Eric Laurente552edb2014-03-10 17:42:56 -0700862
Eric Laurentb732cf52014-09-24 19:08:21 -0700863 sp<IOProfile> profile;
864
865 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700866 // and not explicitly requested
867 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800868 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
869 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700870 goto non_direct_output;
871 }
872
Andy Hung2ddee192015-12-18 17:34:44 -0800873 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
874 // This prevents creating an offloaded track and tearing it down immediately after start
875 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700876 // FIXME: We should check the audio session here but we do not have it in this context.
877 // This may prevent offloading in rare situations where effects are left active by apps
878 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700879
Eric Laurente552edb2014-03-10 17:42:56 -0700880 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800881 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700882 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800883 config->sample_rate,
884 config->format,
885 config->channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -0700886 (audio_output_flags_t)flags);
887 }
888
Eric Laurent1c333e22014-05-20 10:48:17 -0700889 if (profile != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700890 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700891 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700892 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800893 // reuse direct output if currently open by the same client
894 // and configured with same parameters
Eric Laurent3974e3b2017-12-07 17:58:43 -0800895 if ((config->sample_rate == desc->mSamplingRate) &&
896 audio_formats_match(config->format, desc->mFormat) &&
897 (config->channel_mask == desc->mChannelMask) &&
898 (session == desc->mDirectClientSession)) {
899 desc->mDirectOpenCount++;
900 ALOGV("getOutputForDevice() reusing direct output %d for session %d",
901 mOutputs.keyAt(i), session);
902 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700903 }
904 }
905 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800906
907 if (!profile->canOpenNewIo()) {
908 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700909 }
Eric Laurent861a6282015-05-18 15:40:16 -0700910
Eric Laurent3974e3b2017-12-07 17:58:43 -0800911 sp<SwAudioOutputDescriptor> outputDesc =
912 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800913
914 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
915 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
916 : String8("");
917
918 status = outputDesc->open(config, device, address, stream, flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700919
920 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700921 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800922 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
923 (config->format != AUDIO_FORMAT_DEFAULT &&
924 !audio_formats_match(config->format, outputDesc->mFormat)) ||
925 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
926 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
927 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
928 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
929 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700930 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800931 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700932 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800933 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800934 if (audio_is_linear_pcm(config->format) &&
935 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800936 goto non_direct_output;
937 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700938 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700939 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700940 outputDesc->mRefCount[stream] = 0;
941 outputDesc->mStopTime[stream] = 0;
942 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800943 outputDesc->mDirectClientSession = session;
944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700946 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000947 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700948 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700949 return output;
950 }
951
Eric Laurentb732cf52014-09-24 19:08:21 -0700952non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700953
954 // A request for HW A/V sync cannot fallback to a mixed output because time
955 // stamps are embedded in audio data
956 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
957 return AUDIO_IO_HANDLE_NONE;
958 }
959
Eric Laurente552edb2014-03-10 17:42:56 -0700960 // ignoring channel mask due to downmix capability in mixer
961
962 // open a non direct output
963
964 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -0800965 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 // get which output is suitable for the specified stream. The actual
967 // routing change will happen when startOutput() will be called
968 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
969
Eric Laurent8838a382014-09-08 16:44:28 -0700970 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
971 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurentfe231122017-11-17 17:48:06 -0800972 output = selectOutput(outputs, flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurentf4e63452017-11-06 19:31:46 +0000974 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Eric Laurentfe231122017-11-17 17:48:06 -0800975 "sampling rate %d, format %d, channels %x, flags %x",
976 stream, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700977
Eric Laurente552edb2014-03-10 17:42:56 -0700978 return output;
979}
980
Eric Laurente0720872014-03-11 09:30:41 -0700981audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700982 audio_output_flags_t flags,
983 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700984{
985 // select one output among several that provide a path to a particular device or set of
986 // devices (the list was previously build by getOutputsForDevice()).
987 // The priority is as follows:
988 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -0800989 // 2: the output with the bit depth the closest to the requested one
990 // 3: the primary output
991 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -0700992
993 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800994 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700995 }
996 if (outputs.size() == 1) {
997 return outputs[0];
998 }
999
1000 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001001 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1002 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1003 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001004 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1005 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001006
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001007 for (audio_io_handle_t output : outputs) {
1008 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001009 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001010 // if a valid format is specified, skip output if not compatible
1011 if (format != AUDIO_FORMAT_INVALID) {
1012 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001013 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001014 continue;
1015 }
1016 } else if (!audio_is_linear_pcm(format)) {
1017 continue;
1018 }
Eric Laurente6930022016-02-11 10:20:40 -08001019 if (AudioPort::isBetterFormatMatch(
1020 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001021 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001022 bestFormat = outputDesc->mFormat;
1023 }
Eric Laurent8838a382014-09-08 16:44:28 -07001024 }
1025
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001026 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001027 if (commonFlags >= maxCommonFlags) {
1028 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001029 if (format != AUDIO_FORMAT_INVALID
1030 && AudioPort::isBetterFormatMatch(
1031 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001032 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001033 bestFormatForFlags = outputDesc->mFormat;
1034 }
1035 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001036 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001037 maxCommonFlags = commonFlags;
1038 bestFormatForFlags = outputDesc->mFormat;
1039 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001040 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001042 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001043 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 }
1046 }
1047
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001048 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001049 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001050 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001051 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001052 return outputForFormat;
1053 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001054 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001055 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001056 }
1057
1058 return outputs[0];
1059}
1060
Eric Laurente0720872014-03-11 09:30:41 -07001061status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001062 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001063 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001064{
Paul McLeanaa981192015-03-21 09:55:15 -07001065 ALOGV("startOutput() output %d, stream %d, session %d",
1066 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001067 ssize_t index = mOutputs.indexOfKey(output);
1068 if (index < 0) {
1069 ALOGW("startOutput() unknown output %d", output);
1070 return BAD_VALUE;
1071 }
1072
Eric Laurentc75307b2015-03-17 15:29:32 -07001073 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1074
Eric Laurent3974e3b2017-12-07 17:58:43 -08001075 if (!outputDesc->isActive()) {
1076 if (!outputDesc->mProfile->canStartNewIo()) {
1077 return INVALID_OPERATION;
1078 }
1079 outputDesc->mProfile->curActiveCount++;
1080 }
1081
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001082 // Routing?
1083 mOutputRoutes.incRouteActivity(session);
1084
Eric Laurentc75307b2015-03-17 15:29:32 -07001085 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001086 AudioMix *policyMix = NULL;
1087 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001088 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001089 policyMix = outputDesc->mPolicyMix;
1090 address = policyMix->mDeviceAddress.string();
1091 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1092 newDevice = policyMix->mDeviceType;
1093 } else {
1094 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1095 }
Eric Laurent493404d2015-04-21 15:07:36 -07001096 } else if (mOutputRoutes.hasRouteChanged(session)) {
1097 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001098 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001099 } else {
1100 newDevice = AUDIO_DEVICE_NONE;
1101 }
1102
1103 uint32_t delayMs = 0;
1104
Eric Laurentc40d9692016-04-13 19:14:13 -07001105 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001106
1107 if (status != NO_ERROR) {
1108 mOutputRoutes.decRouteActivity(session);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001109 if (!outputDesc->isActive()) {
1110 LOG_ALWAYS_FATAL_IF(outputDesc->mProfile->curActiveCount < 1,
1111 "%s invalid profile active count %u",
1112 __FUNCTION__, outputDesc->mProfile->curActiveCount);
1113 outputDesc->mProfile->curActiveCount--;
1114 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001115 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001116 }
1117 // Automatically enable the remote submix input when output is started on a re routing mix
1118 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001119 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1120 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001121 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001123 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001124 "remote-submix");
1125 }
1126
1127 if (delayMs != 0) {
1128 usleep(delayMs * 1000);
1129 }
1130
1131 return status;
1132}
1133
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001134status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001135 audio_stream_type_t stream,
1136 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001137 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001138 uint32_t *delayMs)
1139{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001140 // cannot start playback of STREAM_TTS if any other output is being used
1141 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001142
1143 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001144 if (stream == AUDIO_STREAM_TTS) {
1145 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001146 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001147 return INVALID_OPERATION;
1148 } else {
1149 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1150 }
1151 } else {
1152 // some playback other than beacon starts
1153 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1154 }
1155
Eric Laurent77305a62016-07-25 16:39:22 -07001156 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001157 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001158 bool force = !outputDesc->isActive() &&
1159 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001160
Andy Hung7c7124e2017-10-20 12:03:34 -07001161 // requiresMuteCheck is false when we can bypass mute strategy.
1162 // It covers a common case when there is no materially active audio
1163 // and muting would result in unnecessary delay and dropped audio.
1164 const uint32_t outputLatencyMs = outputDesc->latency();
1165 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1166
Eric Laurente552edb2014-03-10 17:42:56 -07001167 // increment usage count for this stream on the requested output:
1168 // NOTE that the usage count is the same for duplicated output and hardware output which is
1169 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1170 outputDesc->changeRefCount(stream, 1);
1171
Eric Laurent36829f92017-04-07 19:04:42 -07001172 if (stream == AUDIO_STREAM_MUSIC) {
1173 selectOutputForMusicEffects();
1174 }
1175
Eric Laurent493404d2015-04-21 15:07:36 -07001176 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001177 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001178 if (device == AUDIO_DEVICE_NONE) {
1179 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001180 }
Eric Laurent36829f92017-04-07 19:04:42 -07001181
Eric Laurente552edb2014-03-10 17:42:56 -07001182 routing_strategy strategy = getStrategy(stream);
1183 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001184 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1185 (beaconMuteLatency > 0);
1186 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001187 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001188 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001189 if (desc != outputDesc) {
Andy Hung7c7124e2017-10-20 12:03:34 -07001190 // An output has a shared device if
1191 // - managed by the same hw module
1192 // - supports the currently selected device
1193 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1194 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1195
Eric Laurent77305a62016-07-25 16:39:22 -07001196 // force a device change if any other output is:
1197 // - managed by the same hw module
Eric Laurent77305a62016-07-25 16:39:22 -07001198 // - supports currently selected device
Andy Hung7c7124e2017-10-20 12:03:34 -07001199 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001200 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001201 // In this case, the audio HAL must receive the new device selection so that it can
Andy Hung7c7124e2017-10-20 12:03:34 -07001202 // change the device currently selected by the other output.
1203 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001204 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001205 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001206 force = true;
1207 }
1208 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001209 // a notification so that audio focus effect can propagate, or that a mute/unmute
1210 // event occurred for beacon
Andy Hung7c7124e2017-10-20 12:03:34 -07001211 const uint32_t latencyMs = desc->latency();
1212 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1213
1214 if (shouldWait && isActive && (waitMs < latencyMs)) {
1215 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001216 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001217
1218 // Require mute check if another output is on a shared device
1219 // and currently active to have proper drain and avoid pops.
1220 // Note restoring AudioTracks onto this output needs to invoke
1221 // a volume ramp if there is no mute.
1222 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001223 }
1224 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001225
1226 const uint32_t muteWaitMs =
1227 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001228
1229 // handle special case for sonification while in call
1230 if (isInCall()) {
1231 handleIncallSonification(stream, true, false);
1232 }
1233
1234 // apply volume rules for current stream and device if necessary
1235 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001236 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001237 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001238 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001239
1240 // update the outputs if starting an output with a stream that can affect notification
1241 // routing
1242 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001243
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001244 // force reevaluating accessibility routing when ringtone or alarm starts
1245 if (strategy == STRATEGY_SONIFICATION) {
1246 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1247 }
Eric Laurentdc462862016-07-19 12:29:53 -07001248
1249 if (waitMs > muteWaitMs) {
1250 *delayMs = waitMs - muteWaitMs;
1251 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001252
1253 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1254 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1255 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1256 // change occurs after the MixerThread starts and causes a stream volume
1257 // glitch.
1258 //
1259 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001260 }
Eric Laurentdc462862016-07-19 12:29:53 -07001261
Eric Laurente552edb2014-03-10 17:42:56 -07001262 return NO_ERROR;
1263}
1264
1265
Eric Laurente0720872014-03-11 09:30:41 -07001266status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001267 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001268 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001269{
1270 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1271 ssize_t index = mOutputs.indexOfKey(output);
1272 if (index < 0) {
1273 ALOGW("stopOutput() unknown output %d", output);
1274 return BAD_VALUE;
1275 }
1276
Eric Laurentc75307b2015-03-17 15:29:32 -07001277 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001278
Eric Laurentc75307b2015-03-17 15:29:32 -07001279 if (outputDesc->mRefCount[stream] == 1) {
1280 // Automatically disable the remote submix input when output is stopped on a
1281 // re routing mix of type MIX_TYPE_RECORDERS
1282 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1283 outputDesc->mPolicyMix != NULL &&
1284 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1285 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1286 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001287 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001288 "remote-submix");
1289 }
1290 }
1291
1292 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001293 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001294 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001295 int activityCount = mOutputRoutes.decRouteActivity(session);
1296 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1297
1298 if (forceDeviceUpdate) {
1299 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1300 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001301 }
1302
Eric Laurent3974e3b2017-12-07 17:58:43 -08001303 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1304
1305 if (status == NO_ERROR && !outputDesc->isActive()) {
1306 LOG_ALWAYS_FATAL_IF(outputDesc->mProfile->curActiveCount < 1,
1307 "%s invalid profile active count %u",
1308 __FUNCTION__, outputDesc->mProfile->curActiveCount);
1309 outputDesc->mProfile->curActiveCount--;
1310 }
1311 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001312}
1313
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001314status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001315 audio_stream_type_t stream,
1316 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001317{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001318 // always handle stream stop, check which stream type is stopping
1319 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1320
Eric Laurente552edb2014-03-10 17:42:56 -07001321 // handle special case for sonification while in call
1322 if (isInCall()) {
1323 handleIncallSonification(stream, false, false);
1324 }
1325
1326 if (outputDesc->mRefCount[stream] > 0) {
1327 // decrement usage count of this stream on the output
1328 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001329
Eric Laurente552edb2014-03-10 17:42:56 -07001330 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001331 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001332 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001334 // delay the device switch by twice the latency because stopOutput() is executed when
1335 // the track stop() command is received and at that time the audio track buffer can
1336 // still contain data that needs to be drained. The latency only covers the audio HAL
1337 // and kernel buffers. Also the latency does not always include additional delay in the
1338 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001340
1341 // force restoring the device selection on other active outputs if it differs from the
1342 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001343 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001344 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001345 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001347 desc->isActive() &&
1348 outputDesc->sharesHwModuleWith(desc) &&
1349 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001350 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1351 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001352 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001353 newDevice2,
1354 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001355 delayMs);
1356 // re-apply device specific volume if not done by setOutputDevice()
1357 if (!force) {
1358 applyStreamVolumes(desc, newDevice2, delayMs);
1359 }
Eric Laurente552edb2014-03-10 17:42:56 -07001360 }
1361 }
1362 // update the outputs if stopping one with a stream that can affect notification routing
1363 handleNotificationRoutingForStream(stream);
1364 }
Eric Laurent36829f92017-04-07 19:04:42 -07001365 if (stream == AUDIO_STREAM_MUSIC) {
1366 selectOutputForMusicEffects();
1367 }
Eric Laurente552edb2014-03-10 17:42:56 -07001368 return NO_ERROR;
1369 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001370 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001371 return INVALID_OPERATION;
1372 }
1373}
1374
Eric Laurente83b55d2014-11-14 10:06:21 -08001375void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001376 audio_stream_type_t stream __unused,
1377 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001378{
1379 ALOGV("releaseOutput() %d", output);
1380 ssize_t index = mOutputs.indexOfKey(output);
1381 if (index < 0) {
1382 ALOGW("releaseOutput() releasing unknown output %d", output);
1383 return;
1384 }
1385
Paul McLeanaa981192015-03-21 09:55:15 -07001386 // Routing
1387 mOutputRoutes.removeRoute(session);
1388
Eric Laurentc75307b2015-03-17 15:29:32 -07001389 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001390 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001391 if (desc->mDirectOpenCount <= 0) {
1392 ALOGW("releaseOutput() invalid open count %d for output %d",
1393 desc->mDirectOpenCount, output);
1394 return;
1395 }
1396 if (--desc->mDirectOpenCount == 0) {
1397 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001398 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001399 }
1400 }
1401}
1402
1403
Eric Laurentcaf7f482014-11-25 17:50:47 -08001404status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1405 audio_io_handle_t *input,
1406 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001407 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001408 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001409 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001410 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001411 input_type_t *inputType,
1412 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001413{
Eric Laurentfe231122017-11-17 17:48:06 -08001414 ALOGV("getInputForAttr() source %d, sampling rate %d, format %d, channel mask %x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001415 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001416 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001417
Eric Laurentad2e7b92017-09-14 20:06:42 -07001418 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001419 // handle legacy remote submix case where the address was not always specified
1420 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001421 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001422 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001423 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001424 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001425
Eric Laurentfe231122017-11-17 17:48:06 -08001426 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1427 inputSource = AUDIO_SOURCE_MIC;
1428 }
1429
Paul McLean466dc8e2015-04-17 13:15:36 -06001430 // Explicit routing?
1431 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001432 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001433 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001434 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001435 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001436
Eric Laurentad2e7b92017-09-14 20:06:42 -07001437 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1438 // possible
1439 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1440 *input != AUDIO_IO_HANDLE_NONE) {
1441 ssize_t index = mInputs.indexOfKey(*input);
1442 if (index < 0) {
1443 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1444 status = BAD_VALUE;
1445 goto error;
1446 }
1447 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1448 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1449 if (audioSession == 0) {
1450 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1451 status = BAD_VALUE;
1452 goto error;
1453 }
1454 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1455 // The second call is for the first active client and sets the UID. Any further call
1456 // corresponds to a new client and is only permitted from the same UId.
1457 if (audioSession->openCount() == 1) {
1458 audioSession->setUid(uid);
1459 } else if (audioSession->uid() != uid) {
1460 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1461 uid, session, audioSession->uid());
1462 status = INVALID_OPERATION;
1463 goto error;
1464 }
1465 audioSession->changeOpenCount(1);
1466 *inputType = API_INPUT_LEGACY;
1467 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1468 *portId = AudioPort::getNextUniqueId();
1469 }
1470 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1471 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1472 : AUDIO_PORT_HANDLE_NONE;
1473 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1474
1475 return NO_ERROR;
1476 }
1477
1478 *input = AUDIO_IO_HANDLE_NONE;
1479 *inputType = API_INPUT_INVALID;
1480
Eric Laurentad2e7b92017-09-14 20:06:42 -07001481 halInputSource = inputSource;
1482
1483 // TODO: check for existing client for this port ID
1484 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1485 *portId = AudioPort::getNextUniqueId();
1486 }
1487
1488 audio_devices_t device;
1489
Eric Laurentc447ded2015-01-06 08:47:05 -08001490 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001491 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001492 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1493 if (status != NO_ERROR) {
1494 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001495 }
1496 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001497 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1498 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001499 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001500 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001501 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001502 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001503 status = BAD_VALUE;
1504 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001505 }
Eric Laurentc722f302014-12-10 11:21:49 -08001506 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001507 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001508 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1509 // there is an external policy, but this input is attached to a mix of recorders,
1510 // meaning it receives audio injected into the framework, so the recorder doesn't
1511 // know about it and is therefore considered "legacy"
1512 *inputType = API_INPUT_LEGACY;
1513 } else {
1514 // recording a mix of players defined by an external policy, we're rerouting for
1515 // an external policy
1516 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1517 }
Eric Laurentc722f302014-12-10 11:21:49 -08001518 } else if (audio_is_remote_submix_device(device)) {
1519 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001520 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001521 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1522 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001523 } else {
1524 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001525 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001526
Eric Laurent599c7582015-12-07 18:05:55 -08001527 }
1528
1529 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001530 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001531 policyMix);
1532 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001533 status = INVALID_OPERATION;
1534 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001535 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001536
Eric Laurentad2e7b92017-09-14 20:06:42 -07001537 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001538 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1539 : AUDIO_PORT_HANDLE_NONE;
1540
1541 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1542 *input, *inputType, *selectedDeviceId);
1543
Eric Laurent599c7582015-12-07 18:05:55 -08001544 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001545
1546error:
1547 mInputRoutes.removeRoute(session);
1548 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001549}
1550
1551
1552audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1553 String8 address,
1554 audio_session_t session,
1555 uid_t uid,
1556 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001557 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001558 audio_input_flags_t flags,
1559 AudioMix *policyMix)
1560{
1561 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1562 audio_source_t halInputSource = inputSource;
1563 bool isSoundTrigger = false;
1564
1565 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1566 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1567 if (index >= 0) {
1568 input = mSoundTriggerSessions.valueFor(session);
1569 isSoundTrigger = true;
1570 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1571 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1572 } else {
1573 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001574 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001575 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001576 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001577 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001578 }
1579
Andy Hungf129b032015-04-07 13:45:50 -07001580 // find a compatible input profile (not necessarily identical in parameters)
1581 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001582 // sampling rate and flags may be updated by getInputProfile
1583 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1584 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
1585 audio_format_t profileFormat = config->format;
1586 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001587 audio_input_flags_t profileFlags = flags;
1588 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001589 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001590 profileSamplingRate, profileFormat, profileChannelMask,
1591 profileFlags);
1592 if (profile != 0) {
1593 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001594 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1595 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001596 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1597 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1598 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001599 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001600 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1601 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001602 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001605 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001606 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001607 if (samplingRate == 0) {
1608 samplingRate = profileSamplingRate;
1609 }
Eric Laurente552edb2014-03-10 17:42:56 -07001610
Eric Laurent322b4d22015-04-03 15:57:54 -07001611 if (profile->getModuleHandle() == 0) {
1612 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001613 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001614 }
1615
Eric Laurent599c7582015-12-07 18:05:55 -08001616 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001617 inputSource,
1618 config->format,
1619 samplingRate,
1620 config->channel_mask,
1621 flags,
1622 uid,
1623 isSoundTrigger,
1624 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001625
Eric Laurent74708e72017-04-07 17:13:42 -07001626// FIXME: disable concurrent capture until UI is ready
1627#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001628 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001629 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001630 for (size_t i = 0; i < mInputs.size(); i++) {
1631 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001632 // reuse input if:
1633 // - it shares the same profile
1634 // AND
1635 // - it is not a reroute submix input
1636 // AND
1637 // - it is: not used for sound trigger
1638 // OR
1639 // used for sound trigger and all clients use the same session ID
1640 //
1641 if ((profile == desc->mProfile) &&
1642 (isSoundTrigger == desc->isSoundTrigger()) &&
1643 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001644
1645 sp<AudioSession> as = desc->getAudioSession(session);
1646 if (as != 0) {
1647 // do not allow unmatching properties on same session
1648 if (as->matches(audioSession)) {
1649 as->changeOpenCount(1);
1650 } else {
1651 ALOGW("getInputForDevice() record with different attributes"
1652 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001653 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001654 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001655 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001656 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001657 }
Eric Laurentbb948092017-01-23 18:33:30 -08001658
Eric Laurent555530a2017-02-07 18:17:24 -08001659 // Reuse the already opened input stream on this profile if:
1660 // - the new capture source is background OR
1661 // - the path requested configurations match OR
1662 // - the new source priority is less than the highest source priority on this input
1663 // If the input stream cannot be reused, close it before opening a new stream
1664 // on the same profile for the new client so that the requested path configuration
1665 // can be selected.
1666 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001667 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001668 desc->mChannelMask != config->channel_mask ||
1669 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001670 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001671 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001672 reusedInputDesc = desc;
1673 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001674 } else {
1675 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001676 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1677 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001678 }
Eric Laurent599c7582015-12-07 18:05:55 -08001679 }
1680 }
Eric Laurent599c7582015-12-07 18:05:55 -08001681
Eric Laurent555530a2017-02-07 18:17:24 -08001682 if (reusedInputDesc != 0) {
1683 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1684 for (size_t j = 0; j < sessions.size(); j++) {
1685 audio_session_t currentSession = sessions.keyAt(j);
1686 stopInput(reusedInputDesc->mIoHandle, currentSession);
1687 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1688 }
1689 }
Eric Laurent74708e72017-04-07 17:13:42 -07001690#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001691
Eric Laurent3974e3b2017-12-07 17:58:43 -08001692 if (!profile->canOpenNewIo()) {
1693 return AUDIO_IO_HANDLE_NONE;
1694 }
1695
Eric Laurentfe231122017-11-17 17:48:06 -08001696 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001697
Eric Laurentfe231122017-11-17 17:48:06 -08001698 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1699 lConfig.sample_rate = profileSamplingRate;
1700 lConfig.channel_mask = profileChannelMask;
1701 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001702
Eric Laurent53b810e2017-12-10 17:25:10 -08001703 if (address == "") {
1704 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1705 // the inputs vector must be of size >= 1, but we don't want to crash here
1706 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1707 }
1708
Eric Laurentfe231122017-11-17 17:48:06 -08001709 status_t status = inputDesc->open(&lConfig, device, address,
1710 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001711
1712 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001713 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001714 (profileSamplingRate != lConfig.sample_rate) ||
1715 !audio_formats_match(profileFormat, lConfig.format) ||
1716 (profileChannelMask != lConfig.channel_mask)) {
1717 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
1718 ", format %d, channel mask %x",
1719 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001720 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001721 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001722 }
Eric Laurent599c7582015-12-07 18:05:55 -08001723 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001724 }
1725
Eric Laurentc722f302014-12-10 11:21:49 -08001726 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001727 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001728
Eric Laurent599c7582015-12-07 18:05:55 -08001729 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001730 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001731
Eric Laurent599c7582015-12-07 18:05:55 -08001732 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001733}
1734
Eric Laurentbb948092017-01-23 18:33:30 -08001735//static
1736bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1737{
1738 return (source == AUDIO_SOURCE_HOTWORD) ||
1739 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1740 (source == AUDIO_SOURCE_FM_TUNER);
1741}
1742
Eric Laurentfb66dd92016-01-28 18:32:03 -08001743bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1744 const sp<AudioSession>& audioSession)
1745{
1746 // Do not allow capture if an active voice call is using a software patch and
1747 // the call TX source device is on the same HW module.
1748 // FIXME: would be better to refine to only inputs whose profile connects to the
1749 // call TX device but this information is not in the audio patch
1750 if (mCallTxPatch != 0 &&
1751 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1752 return false;
1753 }
1754
1755 // starting concurrent capture is enabled if:
1756 // 1) capturing for re-routing
1757 // 2) capturing for HOTWORD source
1758 // 3) capturing for FM TUNER source
1759 // 3) All other active captures are either for re-routing or HOTWORD
1760
1761 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001762 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001763 return true;
1764 }
1765
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001766 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001767 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001768 !is_virtual_input_device(activeInput->mDevice)) {
1769 return false;
1770 }
1771 }
1772
1773 return true;
1774}
1775
Chris Thornton2b864642017-06-27 21:26:07 -07001776// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1777bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1778 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1779 bool soundTriggerSupportsConcurrentCapture = false;
1780 unsigned int numModules = 0;
1781 struct sound_trigger_module_descriptor* nModules = NULL;
1782
1783 status_t status = SoundTrigger::listModules(nModules, &numModules);
1784 if (status == NO_ERROR && numModules != 0) {
1785 nModules = (struct sound_trigger_module_descriptor*) calloc(
1786 numModules, sizeof(struct sound_trigger_module_descriptor));
1787 if (nModules == NULL) {
1788 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1789 // ram the next time this function is called.
1790 ALOGE("Failed to allocate buffer for module descriptors");
1791 return false;
1792 }
1793
1794 status = SoundTrigger::listModules(nModules, &numModules);
1795 if (status == NO_ERROR) {
1796 soundTriggerSupportsConcurrentCapture = true;
1797 for (size_t i = 0; i < numModules; ++i) {
1798 soundTriggerSupportsConcurrentCapture &=
1799 nModules[i].properties.concurrent_capture;
1800 }
1801 }
1802 free(nModules);
1803 }
1804 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1805 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1806 }
1807 return mSoundTriggerSupportsConcurrentCapture;
1808}
1809
Eric Laurentfb66dd92016-01-28 18:32:03 -08001810
Eric Laurent4dc68062014-07-28 17:26:49 -07001811status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001812 audio_session_t session,
1813 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001814{
1815 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001816 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001817 ssize_t index = mInputs.indexOfKey(input);
1818 if (index < 0) {
1819 ALOGW("startInput() unknown input %d", input);
1820 return BAD_VALUE;
1821 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001822 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001823
Eric Laurent599c7582015-12-07 18:05:55 -08001824 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1825 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001826 ALOGW("startInput() unknown session %d on input %d", session, input);
1827 return BAD_VALUE;
1828 }
1829
Eric Laurent74708e72017-04-07 17:13:42 -07001830// FIXME: disable concurrent capture until UI is ready
1831#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001832 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1833 ALOGW("startInput(%d) failed: other input already started", input);
1834 return INVALID_OPERATION;
1835 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001836
Eric Laurentfb66dd92016-01-28 18:32:03 -08001837 if (isInCall()) {
1838 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1839 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001840 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001841 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001842 }
Eric Laurent74708e72017-04-07 17:13:42 -07001843#else
1844 if (!is_virtual_input_device(inputDesc->mDevice)) {
1845 if (mCallTxPatch != 0 &&
1846 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1847 ALOGW("startInput(%d) failed: call in progress", input);
1848 return INVALID_OPERATION;
1849 }
1850
1851 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001852 for (const auto& activeDesc : activeInputs) {
Eric Laurent74708e72017-04-07 17:13:42 -07001853 if (is_virtual_input_device(activeDesc->mDevice)) {
1854 continue;
1855 }
1856
Eric Laurentcb4dae22017-07-01 19:39:32 -07001857 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1858 activeDesc->getId() == inputDesc->getId()) {
1859 continue;
1860 }
1861
Eric Laurent74708e72017-04-07 17:13:42 -07001862 audio_source_t activeSource = activeDesc->inputSource(true);
1863 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1864 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1865 if (activeDesc->hasPreemptedSession(session)) {
1866 ALOGW("startInput(%d) failed for HOTWORD: "
1867 "other input %d already started for HOTWORD",
1868 input, activeDesc->mIoHandle);
1869 return INVALID_OPERATION;
1870 }
1871 } else {
1872 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1873 input, activeDesc->mIoHandle);
1874 return INVALID_OPERATION;
1875 }
1876 } else {
1877 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1878 ALOGW("startInput(%d) failed: other input %d already started",
1879 input, activeDesc->mIoHandle);
1880 return INVALID_OPERATION;
1881 }
1882 }
1883 }
1884
Chris Thornton2b864642017-06-27 21:26:07 -07001885 // We only need to check if the sound trigger session supports concurrent capture if the
1886 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1887 // that's running.
1888 const bool allowConcurrentWithSoundTrigger =
1889 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1890
Eric Laurent74708e72017-04-07 17:13:42 -07001891 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001892 for (const auto& activeDesc : activeInputs) {
Eric Laurent74708e72017-04-07 17:13:42 -07001893 if (is_virtual_input_device(activeDesc->mDevice)) {
1894 continue;
1895 }
1896
Chris Thornton2b864642017-06-27 21:26:07 -07001897 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1898 continue;
1899 }
1900
Eric Laurent74708e72017-04-07 17:13:42 -07001901 audio_source_t activeSource = activeDesc->inputSource(true);
1902 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1903 AudioSessionCollection activeSessions =
1904 activeDesc->getAudioSessions(true /*activeOnly*/);
1905 audio_session_t activeSession = activeSessions.keyAt(0);
1906 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1907 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1908 sessions.add(activeSession);
1909 inputDesc->setPreemptedSessions(sessions);
1910 stopInput(activeHandle, activeSession);
1911 releaseInput(activeHandle, activeSession);
1912 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1913 input, activeDesc->mIoHandle);
1914 }
1915 }
1916 }
1917#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001918
Eric Laurent313d1e72016-01-29 09:56:57 -08001919 // increment activity count before calling getNewInputDevice() below as only active sessions
1920 // are considered for device selection
1921 audioSession->changeActiveCount(1);
1922
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001923 // Routing?
1924 mInputRoutes.incRouteActivity(session);
1925
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001926 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001927 // indicate active capture to sound trigger service if starting capture from a mic on
1928 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001929 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001930 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001931
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001932 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08001933 if (!inputDesc->mProfile->canStartNewIo()) {
1934 mInputRoutes.decRouteActivity(session);
1935 audioSession->changeActiveCount(-1);
1936 return INVALID_OPERATION;
1937 }
1938 inputDesc->mProfile->curActiveCount++;
1939
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001940 // if input maps to a dynamic policy with an activity listener, notify of state change
1941 if ((inputDesc->mPolicyMix != NULL)
1942 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1943 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1944 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001945 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001946
Eric Laurentf7c50102016-09-30 15:19:43 -07001947 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1948 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001949 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001950 SoundTrigger::setCaptureState(true);
1951 }
1952
1953 // automatically enable the remote submix output when input is started if not
1954 // used by a policy mix of type MIX_TYPE_RECORDERS
1955 // For remote submix (a virtual device), we open only one input per capture request.
1956 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1957 String8 address = String8("");
1958 if (inputDesc->mPolicyMix == NULL) {
1959 address = String8("0");
1960 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1961 address = inputDesc->mPolicyMix->mDeviceAddress;
1962 }
1963 if (address != "") {
1964 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1965 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1966 address, "remote-submix");
1967 }
Eric Laurentc722f302014-12-10 11:21:49 -08001968 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001969 }
Eric Laurente552edb2014-03-10 17:42:56 -07001970 }
1971
Eric Laurent599c7582015-12-07 18:05:55 -08001972 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001973
Eric Laurente552edb2014-03-10 17:42:56 -07001974 return NO_ERROR;
1975}
1976
Eric Laurent4dc68062014-07-28 17:26:49 -07001977status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1978 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001979{
1980 ALOGV("stopInput() input %d", input);
1981 ssize_t index = mInputs.indexOfKey(input);
1982 if (index < 0) {
1983 ALOGW("stopInput() unknown input %d", input);
1984 return BAD_VALUE;
1985 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001986 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001987
Eric Laurent599c7582015-12-07 18:05:55 -08001988 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001989 if (index < 0) {
1990 ALOGW("stopInput() unknown session %d on input %d", session, input);
1991 return BAD_VALUE;
1992 }
1993
Eric Laurent599c7582015-12-07 18:05:55 -08001994 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001995 ALOGW("stopInput() input %d already stopped", input);
1996 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001997 }
1998
Eric Laurent599c7582015-12-07 18:05:55 -08001999 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002000
2001 // Routing?
2002 mInputRoutes.decRouteActivity(session);
2003
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002004 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002005
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002006 if (inputDesc->isActive()) {
2007 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2008 } else {
Eric Laurent3974e3b2017-12-07 17:58:43 -08002009 LOG_ALWAYS_FATAL_IF(inputDesc->mProfile->curActiveCount < 1,
2010 "%s invalid profile active count %u",
2011 __FUNCTION__, inputDesc->mProfile->curActiveCount);
2012 inputDesc->mProfile->curActiveCount--;
2013
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002014 // if input maps to a dynamic policy with an activity listener, notify of state change
2015 if ((inputDesc->mPolicyMix != NULL)
2016 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2017 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2018 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002019 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002020
2021 // automatically disable the remote submix output when input is stopped if not
2022 // used by a policy mix of type MIX_TYPE_RECORDERS
2023 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2024 String8 address = String8("");
2025 if (inputDesc->mPolicyMix == NULL) {
2026 address = String8("0");
2027 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2028 address = inputDesc->mPolicyMix->mDeviceAddress;
2029 }
2030 if (address != "") {
2031 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2032 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2033 address, "remote-submix");
2034 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002035 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002036
Eric Laurentf7c50102016-09-30 15:19:43 -07002037 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002038 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002039
Eric Laurentf7c50102016-09-30 15:19:43 -07002040 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2041 // primary HW module
2042 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2043 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2044 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002045 SoundTrigger::setCaptureState(false);
2046 }
2047 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002048 }
Eric Laurente552edb2014-03-10 17:42:56 -07002049 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002050 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002051}
2052
Eric Laurent4dc68062014-07-28 17:26:49 -07002053void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2054 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002055{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002056
Eric Laurente552edb2014-03-10 17:42:56 -07002057 ALOGV("releaseInput() %d", input);
2058 ssize_t index = mInputs.indexOfKey(input);
2059 if (index < 0) {
2060 ALOGW("releaseInput() releasing unknown input %d", input);
2061 return;
2062 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002063
2064 // Routing
2065 mInputRoutes.removeRoute(session);
2066
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002067 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2068 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002069
Eric Laurent599c7582015-12-07 18:05:55 -08002070 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002071 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002072 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2073 return;
2074 }
Eric Laurent599c7582015-12-07 18:05:55 -08002075
2076 if (audioSession->openCount() == 0) {
2077 ALOGW("releaseInput() invalid open count %d on session %d",
2078 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002079 return;
2080 }
Eric Laurent599c7582015-12-07 18:05:55 -08002081
2082 if (audioSession->changeOpenCount(-1) == 0) {
2083 inputDesc->removeAudioSession(session);
2084 }
2085
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002086 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002087 ALOGV("releaseInput() exit > 0");
2088 return;
2089 }
2090
Eric Laurent05b90f82014-08-27 15:32:29 -07002091 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002092 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002093 ALOGV("releaseInput() exit");
2094}
2095
Eric Laurentd4692962014-05-05 18:13:44 -07002096void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002097 bool patchRemoved = false;
2098
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002099 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002100 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002101 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002102 if (patch_index >= 0) {
2103 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002104 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002105 mAudioPatches.removeItemsAt(patch_index);
2106 patchRemoved = true;
2107 }
Eric Laurentfe231122017-11-17 17:48:06 -08002108 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002109 }
2110 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002111 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002112 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002113
2114 if (patchRemoved) {
2115 mpClientInterface->onAudioPatchListUpdate();
2116 }
Eric Laurentd4692962014-05-05 18:13:44 -07002117}
2118
Eric Laurente0720872014-03-11 09:30:41 -07002119void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002120 int indexMin,
2121 int indexMax)
2122{
2123 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002124 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002125
2126 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002127 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2128 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002129 continue;
2130 }
2131 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002132 }
Eric Laurente552edb2014-03-10 17:42:56 -07002133}
2134
Eric Laurente0720872014-03-11 09:30:41 -07002135status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002136 int index,
2137 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002138{
2139
François Gaffied1ab2bd2015-12-02 18:20:06 +01002140 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2141 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002142 return BAD_VALUE;
2143 }
2144 if (!audio_is_output_device(device)) {
2145 return BAD_VALUE;
2146 }
2147
2148 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002149 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002150
Eric Laurent1fd372e2016-04-06 14:23:53 -07002151 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002152 stream, device, index);
2153
Eric Laurent28d09f02016-03-08 10:43:05 -08002154 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002155 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2156 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002157 continue;
2158 }
2159 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2160 }
Eric Laurente552edb2014-03-10 17:42:56 -07002161
Eric Laurent1fd372e2016-04-06 14:23:53 -07002162 // update volume on all outputs and streams matching the following:
2163 // - The requested stream (or a stream matching for volume control) is active on the output
2164 // - The device (or devices) selected by the strategy corresponding to this stream includes
2165 // the requested device
2166 // - For non default requested device, currently selected device on the output is either the
2167 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002168 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2169 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002170 status_t status = NO_ERROR;
2171 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002172 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2173 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002174 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2175 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002176 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002177 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002178 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2179 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002180 continue;
2181 }
Eric Laurent794fde22016-03-11 09:50:45 -08002182 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002183 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2184 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002185 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2186 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002187 continue;
2188 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002189 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002190 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002191 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002192 applyVolume = (curDevice & curStreamDevice) != 0;
2193 } else {
2194 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002195 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002196 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002197
Eric Laurente76f29c2016-09-14 17:17:53 -07002198 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002199 //FIXME: workaround for truncated touch sounds
2200 // delayed volume change for system stream to be removed when the problem is
2201 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002202 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002203 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2204 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002205 if (volStatus != NO_ERROR) {
2206 status = volStatus;
2207 }
2208 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002209 }
Eric Laurente552edb2014-03-10 17:42:56 -07002210 }
2211 return status;
2212}
2213
Eric Laurente0720872014-03-11 09:30:41 -07002214status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002215 int *index,
2216 audio_devices_t device)
2217{
2218 if (index == NULL) {
2219 return BAD_VALUE;
2220 }
2221 if (!audio_is_output_device(device)) {
2222 return BAD_VALUE;
2223 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002224 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002225 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002226 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002227 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2228 }
François Gaffiedfd74092015-03-19 12:10:59 +01002229 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002230
François Gaffied1ab2bd2015-12-02 18:20:06 +01002231 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002232 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2233 return NO_ERROR;
2234}
2235
Eric Laurent36829f92017-04-07 19:04:42 -07002236audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002237{
2238 // select one output among several suitable for global effects.
2239 // The priority is as follows:
2240 // 1: An offloaded output. If the effect ends up not being offloadable,
2241 // AudioFlinger will invalidate the track and the offloaded output
2242 // will be closed causing the effect to be moved to a PCM output.
2243 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002244 // 3: The primary output
2245 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002246
Eric Laurent3b73df72014-03-11 09:06:29 -07002247 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002248 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002249 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002250
Eric Laurent36829f92017-04-07 19:04:42 -07002251 if (outputs.size() == 0) {
2252 return AUDIO_IO_HANDLE_NONE;
2253 }
Eric Laurente552edb2014-03-10 17:42:56 -07002254
Eric Laurent36829f92017-04-07 19:04:42 -07002255 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2256 bool activeOnly = true;
2257
2258 while (output == AUDIO_IO_HANDLE_NONE) {
2259 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2260 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2261 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2262
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002263 for (audio_io_handle_t output : outputs) {
2264 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002265 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2266 continue;
2267 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002268 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2269 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002270 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002271 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002272 }
2273 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002274 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002275 }
2276 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002277 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002278 }
2279 }
2280 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2281 output = outputOffloaded;
2282 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2283 output = outputDeepBuffer;
2284 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2285 output = outputPrimary;
2286 } else {
2287 output = outputs[0];
2288 }
2289 activeOnly = false;
2290 }
2291
2292 if (output != mMusicEffectOutput) {
2293 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2294 mMusicEffectOutput = output;
2295 }
2296
2297 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002298 return output;
2299}
2300
Eric Laurent36829f92017-04-07 19:04:42 -07002301audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2302{
2303 return selectOutputForMusicEffects();
2304}
2305
Eric Laurente0720872014-03-11 09:30:41 -07002306status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002307 audio_io_handle_t io,
2308 uint32_t strategy,
2309 int session,
2310 int id)
2311{
2312 ssize_t index = mOutputs.indexOfKey(io);
2313 if (index < 0) {
2314 index = mInputs.indexOfKey(io);
2315 if (index < 0) {
2316 ALOGW("registerEffect() unknown io %d", io);
2317 return INVALID_OPERATION;
2318 }
2319 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002320 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002321}
2322
Eric Laurentc75307b2015-03-17 15:29:32 -07002323bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2324{
Eric Laurent28d09f02016-03-08 10:43:05 -08002325 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002326 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2327 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002328 continue;
2329 }
2330 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2331 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002332 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002333}
2334
2335bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2336{
2337 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2338}
2339
Eric Laurente0720872014-03-11 09:30:41 -07002340bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002341{
2342 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002343 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002344 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002345 return true;
2346 }
2347 }
2348 return false;
2349}
2350
Eric Laurent275e8e92014-11-30 15:14:47 -08002351// Register a list of custom mixes with their attributes and format.
2352// When a mix is registered, corresponding input and output profiles are
2353// added to the remote submix hw module. The profile contains only the
2354// parameters (sampling rate, format...) specified by the mix.
2355// The corresponding input remote submix device is also connected.
2356//
2357// When a remote submix device is connected, the address is checked to select the
2358// appropriate profile and the corresponding input or output stream is opened.
2359//
2360// When capture starts, getInputForAttr() will:
2361// - 1 look for a mix matching the address passed in attribtutes tags if any
2362// - 2 if none found, getDeviceForInputSource() will:
2363// - 2.1 look for a mix matching the attributes source
2364// - 2.2 if none found, default to device selection by policy rules
2365// At this time, the corresponding output remote submix device is also connected
2366// and active playback use cases can be transferred to this mix if needed when reconnecting
2367// after AudioTracks are invalidated
2368//
2369// When playback starts, getOutputForAttr() will:
2370// - 1 look for a mix matching the address passed in attribtutes tags if any
2371// - 2 if none found, look for a mix matching the attributes usage
2372// - 3 if none found, default to device and output selection by policy rules.
2373
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002374status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002375{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002376 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2377 status_t res = NO_ERROR;
2378
2379 sp<HwModule> rSubmixModule;
2380 // examine each mix's route type
2381 for (size_t i = 0; i < mixes.size(); i++) {
2382 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2383 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2384 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002385 break;
2386 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002387 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002388 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002389 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002390 rSubmixModule = mHwModules.getModuleFromName(
2391 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2392 if (rSubmixModule == 0) {
2393 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2394 i);
2395 res = INVALID_OPERATION;
2396 break;
2397 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002398 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002399
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002400 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002401
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002402 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002403 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002404 res = INVALID_OPERATION;
2405 break;
2406 }
2407 audio_config_t outputConfig = mixes[i].mFormat;
2408 audio_config_t inputConfig = mixes[i].mFormat;
2409 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2410 // stereo and let audio flinger do the channel conversion if needed.
2411 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2412 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2413 rSubmixModule->addOutputProfile(address, &outputConfig,
2414 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2415 rSubmixModule->addInputProfile(address, &inputConfig,
2416 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002417
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002418 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2419 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2420 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2421 address.string(), "remote-submix");
2422 } else {
2423 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2424 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2425 address.string(), "remote-submix");
2426 }
2427 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002428 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002429 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002430 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2431 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002432
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002433 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002434 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2435 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2436 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2437 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2438 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2439 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002440 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2441 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002442 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2443 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002444 } else {
2445 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002446 }
2447 break;
2448 }
2449 }
2450
2451 if (res != NO_ERROR) {
2452 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002453 i, device, address.string());
2454 res = INVALID_OPERATION;
2455 break;
2456 } else if (!foundOutput) {
2457 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2458 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002459 res = INVALID_OPERATION;
2460 break;
2461 }
Eric Laurentc722f302014-12-10 11:21:49 -08002462 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002463 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002464 if (res != NO_ERROR) {
2465 unregisterPolicyMixes(mixes);
2466 }
2467 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002468}
2469
2470status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2471{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002472 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002473 status_t res = NO_ERROR;
2474 sp<HwModule> rSubmixModule;
2475 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002476 for (const auto& mix : mixes) {
2477 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002478
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002479 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002480 rSubmixModule = mHwModules.getModuleFromName(
2481 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2482 if (rSubmixModule == 0) {
2483 res = INVALID_OPERATION;
2484 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 }
2486 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002487
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002488 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002489
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2491 res = INVALID_OPERATION;
2492 continue;
2493 }
2494
2495 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2496 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2498 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2499 address.string(), "remote-submix");
2500 }
2501 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2502 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2503 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2504 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2505 address.string(), "remote-submix");
2506 }
2507 rSubmixModule->removeOutputProfile(address);
2508 rSubmixModule->removeInputProfile(address);
2509
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002510 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2511 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 res = INVALID_OPERATION;
2513 continue;
2514 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002515 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002516 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002517 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002518}
2519
Eric Laurente552edb2014-03-10 17:42:56 -07002520
Eric Laurente0720872014-03-11 09:30:41 -07002521status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002522{
2523 const size_t SIZE = 256;
2524 char buffer[SIZE];
2525 String8 result;
2526
2527 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2528 result.append(buffer);
2529
Eric Laurent87ffa392015-05-22 10:32:38 -07002530 snprintf(buffer, SIZE, " Primary Output: %d\n",
2531 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002532 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002533 std::string stateLiteral;
2534 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2535 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002536 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002537 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002538 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002539 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002540 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002541 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002542 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002543 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002544 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002545 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002546 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002547 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002548 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002549 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002550 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002551 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2552 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2553 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002554 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2555 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002556 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2557 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002558
François Gaffie2110e042015-03-24 08:41:51 +01002559 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002560
François Gaffie112b0af2015-11-19 16:13:25 +01002561 mAvailableOutputDevices.dump(fd, String8("Available output"));
2562 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002563 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002564 mOutputs.dump(fd);
2565 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002566 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002567 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002568 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002569 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002570
2571 return NO_ERROR;
2572}
2573
2574// This function checks for the parameters which can be offloaded.
2575// This can be enhanced depending on the capability of the DSP and policy
2576// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002577bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002578{
2579 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002580 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002581 offloadInfo.sample_rate, offloadInfo.channel_mask,
2582 offloadInfo.format,
2583 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2584 offloadInfo.has_video);
2585
Andy Hung2ddee192015-12-18 17:34:44 -08002586 if (mMasterMono) {
2587 return false; // no offloading if mono is set.
2588 }
2589
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // Check if offload has been disabled
2591 char propValue[PROPERTY_VALUE_MAX];
2592 if (property_get("audio.offload.disable", propValue, "0")) {
2593 if (atoi(propValue) != 0) {
2594 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2595 return false;
2596 }
2597 }
2598
2599 // Check if stream type is music, then only allow offload as of now.
2600 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2601 {
2602 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2603 return false;
2604 }
2605
2606 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002607 const bool allowOffloadWithVideo =
2608 property_get_bool("audio.offload.video", false /* default_value */);
2609 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002610 ALOGV("isOffloadSupported: has_video == true, returning false");
2611 return false;
2612 }
2613
2614 //If duration is less than minimum value defined in property, return false
2615 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2616 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2617 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2618 return false;
2619 }
2620 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2621 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2622 return false;
2623 }
2624
2625 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2626 // creating an offloaded track and tearing it down immediately after start when audioflinger
2627 // detects there is an active non offloadable effect.
2628 // FIXME: We should check the audio session here but we do not have it in this context.
2629 // This may prevent offloading in rare situations where effects are left active by apps
2630 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002631 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002632 return false;
2633 }
2634
2635 // See if there is a profile to support this.
2636 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002637 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002638 offloadInfo.sample_rate,
2639 offloadInfo.format,
2640 offloadInfo.channel_mask,
2641 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002642 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2643 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002644}
2645
Eric Laurent6a94d692014-05-20 11:18:06 -07002646status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2647 audio_port_type_t type,
2648 unsigned int *num_ports,
2649 struct audio_port *ports,
2650 unsigned int *generation)
2651{
2652 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2653 generation == NULL) {
2654 return BAD_VALUE;
2655 }
2656 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2657 if (ports == NULL) {
2658 *num_ports = 0;
2659 }
2660
2661 size_t portsWritten = 0;
2662 size_t portsMax = *num_ports;
2663 *num_ports = 0;
2664 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002665 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2666 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002667 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002668 for (const auto& dev : mAvailableOutputDevices) {
2669 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002670 continue;
2671 }
2672 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002673 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002674 }
2675 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002676 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002677 }
2678 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002679 for (const auto& dev : mAvailableInputDevices) {
2680 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002681 continue;
2682 }
2683 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002684 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002685 }
2686 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002688 }
2689 }
2690 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2691 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2692 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2693 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2694 }
2695 *num_ports += mInputs.size();
2696 }
2697 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002698 size_t numOutputs = 0;
2699 for (size_t i = 0; i < mOutputs.size(); i++) {
2700 if (!mOutputs[i]->isDuplicated()) {
2701 numOutputs++;
2702 if (portsWritten < portsMax) {
2703 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2704 }
2705 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 }
Eric Laurent84c70242014-06-23 08:46:27 -07002707 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002708 }
2709 }
2710 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002711 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002712 return NO_ERROR;
2713}
2714
2715status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2716{
2717 return NO_ERROR;
2718}
2719
Eric Laurent6a94d692014-05-20 11:18:06 -07002720status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2721 audio_patch_handle_t *handle,
2722 uid_t uid)
2723{
2724 ALOGV("createAudioPatch()");
2725
2726 if (handle == NULL || patch == NULL) {
2727 return BAD_VALUE;
2728 }
2729 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2730
Eric Laurent874c42872014-08-08 15:13:39 -07002731 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2732 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2733 return BAD_VALUE;
2734 }
2735 // only one source per audio patch supported for now
2736 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 return INVALID_OPERATION;
2738 }
Eric Laurent874c42872014-08-08 15:13:39 -07002739
2740 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002741 return INVALID_OPERATION;
2742 }
Eric Laurent874c42872014-08-08 15:13:39 -07002743 for (size_t i = 0; i < patch->num_sinks; i++) {
2744 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2745 return INVALID_OPERATION;
2746 }
2747 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002748
2749 sp<AudioPatch> patchDesc;
2750 ssize_t index = mAudioPatches.indexOfKey(*handle);
2751
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2753 patch->sources[0].role,
2754 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002755#if LOG_NDEBUG == 0
2756 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002757 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002758 patch->sinks[i].role,
2759 patch->sinks[i].type);
2760 }
2761#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002762
2763 if (index >= 0) {
2764 patchDesc = mAudioPatches.valueAt(index);
2765 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2766 mUidCached, patchDesc->mUid, uid);
2767 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2768 return INVALID_OPERATION;
2769 }
2770 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002771 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002772 }
2773
2774 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002775 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002776 if (outputDesc == NULL) {
2777 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2778 return BAD_VALUE;
2779 }
Eric Laurent84c70242014-06-23 08:46:27 -07002780 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2781 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002782 if (patchDesc != 0) {
2783 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2784 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2785 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2786 return BAD_VALUE;
2787 }
2788 }
Eric Laurent874c42872014-08-08 15:13:39 -07002789 DeviceVector devices;
2790 for (size_t i = 0; i < patch->num_sinks; i++) {
2791 // Only support mix to devices connection
2792 // TODO add support for mix to mix connection
2793 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2794 ALOGV("createAudioPatch() source mix but sink is not a device");
2795 return INVALID_OPERATION;
2796 }
2797 sp<DeviceDescriptor> devDesc =
2798 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2799 if (devDesc == 0) {
2800 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2801 return BAD_VALUE;
2802 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002803
François Gaffie53615e22015-03-19 09:24:12 +01002804 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002805 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002806 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002807 NULL, // updatedSamplingRate
2808 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002809 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002810 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002811 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002812 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002813 ALOGV("createAudioPatch() profile not supported for device %08x",
2814 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002815 return INVALID_OPERATION;
2816 }
2817 devices.add(devDesc);
2818 }
2819 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002820 return INVALID_OPERATION;
2821 }
Eric Laurent874c42872014-08-08 15:13:39 -07002822
Eric Laurent6a94d692014-05-20 11:18:06 -07002823 // TODO: reconfigure output format and channels here
2824 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002825 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002826 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 index = mAudioPatches.indexOfKey(*handle);
2828 if (index >= 0) {
2829 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2830 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2831 }
2832 patchDesc = mAudioPatches.valueAt(index);
2833 patchDesc->mUid = uid;
2834 ALOGV("createAudioPatch() success");
2835 } else {
2836 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2837 return INVALID_OPERATION;
2838 }
2839 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2840 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2841 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002842 // only one sink supported when connecting an input device to a mix
2843 if (patch->num_sinks > 1) {
2844 return INVALID_OPERATION;
2845 }
François Gaffie53615e22015-03-19 09:24:12 +01002846 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 if (inputDesc == NULL) {
2848 return BAD_VALUE;
2849 }
2850 if (patchDesc != 0) {
2851 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2852 return BAD_VALUE;
2853 }
2854 }
2855 sp<DeviceDescriptor> devDesc =
2856 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2857 if (devDesc == 0) {
2858 return BAD_VALUE;
2859 }
2860
François Gaffie53615e22015-03-19 09:24:12 +01002861 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002862 devDesc->mAddress,
2863 patch->sinks[0].sample_rate,
2864 NULL, /*updatedSampleRate*/
2865 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002866 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002867 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002868 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002869 // FIXME for the parameter type,
2870 // and the NONE
2871 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002872 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002873 return INVALID_OPERATION;
2874 }
2875 // TODO: reconfigure output format and channels here
2876 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002877 devDesc->type(), inputDesc->mIoHandle);
2878 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 index = mAudioPatches.indexOfKey(*handle);
2880 if (index >= 0) {
2881 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2882 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2883 }
2884 patchDesc = mAudioPatches.valueAt(index);
2885 patchDesc->mUid = uid;
2886 ALOGV("createAudioPatch() success");
2887 } else {
2888 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2889 return INVALID_OPERATION;
2890 }
2891 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2892 // device to device connection
2893 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002894 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002895 return BAD_VALUE;
2896 }
2897 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 sp<DeviceDescriptor> srcDeviceDesc =
2899 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002900 if (srcDeviceDesc == 0) {
2901 return BAD_VALUE;
2902 }
Eric Laurent874c42872014-08-08 15:13:39 -07002903
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 //update source and sink with our own data as the data passed in the patch may
2905 // be incomplete.
2906 struct audio_patch newPatch = *patch;
2907 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002908
Eric Laurent874c42872014-08-08 15:13:39 -07002909 for (size_t i = 0; i < patch->num_sinks; i++) {
2910 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2911 ALOGV("createAudioPatch() source device but one sink is not a device");
2912 return INVALID_OPERATION;
2913 }
2914
2915 sp<DeviceDescriptor> sinkDeviceDesc =
2916 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2917 if (sinkDeviceDesc == 0) {
2918 return BAD_VALUE;
2919 }
2920 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2921
Eric Laurent3bcf8592015-04-03 12:13:24 -07002922 // create a software bridge in PatchPanel if:
2923 // - source and sink devices are on differnt HW modules OR
2924 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002925 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002926 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002927 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002928 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002929 return INVALID_OPERATION;
2930 }
Eric Laurent874c42872014-08-08 15:13:39 -07002931 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002932 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002933 // if the sink device is reachable via an opened output stream, request to go via
2934 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002935 audio_io_handle_t output = selectOutput(outputs,
2936 AUDIO_OUTPUT_FLAG_NONE,
2937 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002938 if (output != AUDIO_IO_HANDLE_NONE) {
2939 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2940 if (outputDesc->isDuplicated()) {
2941 return INVALID_OPERATION;
2942 }
2943 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002944 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002945 newPatch.num_sources = 2;
2946 }
Eric Laurent83b88082014-06-20 18:31:16 -07002947 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002948 }
2949 // TODO: check from routing capabilities in config file and other conflicting patches
2950
2951 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2952 if (index >= 0) {
2953 afPatchHandle = patchDesc->mAfPatchHandle;
2954 }
2955
2956 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2957 &afPatchHandle,
2958 0);
2959 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2960 status, afPatchHandle);
2961 if (status == NO_ERROR) {
2962 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002963 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 addAudioPatch(patchDesc->mHandle, patchDesc);
2965 } else {
2966 patchDesc->mPatch = newPatch;
2967 }
2968 patchDesc->mAfPatchHandle = afPatchHandle;
2969 *handle = patchDesc->mHandle;
2970 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002971 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002972 } else {
2973 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2974 status);
2975 return INVALID_OPERATION;
2976 }
2977 } else {
2978 return BAD_VALUE;
2979 }
2980 } else {
2981 return BAD_VALUE;
2982 }
2983 return NO_ERROR;
2984}
2985
2986status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2987 uid_t uid)
2988{
2989 ALOGV("releaseAudioPatch() patch %d", handle);
2990
2991 ssize_t index = mAudioPatches.indexOfKey(handle);
2992
2993 if (index < 0) {
2994 return BAD_VALUE;
2995 }
2996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2997 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2998 mUidCached, patchDesc->mUid, uid);
2999 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3000 return INVALID_OPERATION;
3001 }
3002
3003 struct audio_patch *patch = &patchDesc->mPatch;
3004 patchDesc->mUid = mUidCached;
3005 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003006 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 if (outputDesc == NULL) {
3008 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3009 return BAD_VALUE;
3010 }
3011
Eric Laurentc75307b2015-03-17 15:29:32 -07003012 setOutputDevice(outputDesc,
3013 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 true,
3015 0,
3016 NULL);
3017 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3018 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003019 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 if (inputDesc == NULL) {
3021 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3022 return BAD_VALUE;
3023 }
3024 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003025 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 true,
3027 NULL);
3028 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3030 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3031 status, patchDesc->mAfPatchHandle);
3032 removeAudioPatch(patchDesc->mHandle);
3033 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003034 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003035 } else {
3036 return BAD_VALUE;
3037 }
3038 } else {
3039 return BAD_VALUE;
3040 }
3041 return NO_ERROR;
3042}
3043
3044status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3045 struct audio_patch *patches,
3046 unsigned int *generation)
3047{
François Gaffie53615e22015-03-19 09:24:12 +01003048 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 return BAD_VALUE;
3050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003052 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003053}
3054
Eric Laurente1715a42014-05-20 11:30:42 -07003055status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003056{
Eric Laurente1715a42014-05-20 11:30:42 -07003057 ALOGV("setAudioPortConfig()");
3058
3059 if (config == NULL) {
3060 return BAD_VALUE;
3061 }
3062 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3063 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003064 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3065 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003066 }
3067
Eric Laurenta121f902014-06-03 13:32:54 -07003068 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003069 if (config->type == AUDIO_PORT_TYPE_MIX) {
3070 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003071 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003072 if (outputDesc == NULL) {
3073 return BAD_VALUE;
3074 }
Eric Laurent84c70242014-06-23 08:46:27 -07003075 ALOG_ASSERT(!outputDesc->isDuplicated(),
3076 "setAudioPortConfig() called on duplicated output %d",
3077 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003078 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003079 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003080 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003081 if (inputDesc == NULL) {
3082 return BAD_VALUE;
3083 }
Eric Laurenta121f902014-06-03 13:32:54 -07003084 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003085 } else {
3086 return BAD_VALUE;
3087 }
3088 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3089 sp<DeviceDescriptor> deviceDesc;
3090 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3091 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3092 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3093 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3094 } else {
3095 return BAD_VALUE;
3096 }
3097 if (deviceDesc == NULL) {
3098 return BAD_VALUE;
3099 }
Eric Laurenta121f902014-06-03 13:32:54 -07003100 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003101 } else {
3102 return BAD_VALUE;
3103 }
3104
Eric Laurenta121f902014-06-03 13:32:54 -07003105 struct audio_port_config backupConfig;
3106 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3107 if (status == NO_ERROR) {
3108 struct audio_port_config newConfig;
3109 audioPortConfig->toAudioPortConfig(&newConfig, config);
3110 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003111 }
Eric Laurenta121f902014-06-03 13:32:54 -07003112 if (status != NO_ERROR) {
3113 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003114 }
Eric Laurente1715a42014-05-20 11:30:42 -07003115
3116 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003117}
3118
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003119void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3120{
Eric Laurentd60560a2015-04-10 11:31:20 -07003121 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003122 clearAudioPatches(uid);
3123 clearSessionRoutes(uid);
3124}
3125
Eric Laurent6a94d692014-05-20 11:18:06 -07003126void AudioPolicyManager::clearAudioPatches(uid_t uid)
3127{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003128 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003129 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3130 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003131 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 }
3133 }
3134}
3135
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003136void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3137 audio_io_handle_t ouptutToSkip)
3138{
3139 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3140 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3141 for (size_t j = 0; j < mOutputs.size(); j++) {
3142 if (mOutputs.keyAt(j) == ouptutToSkip) {
3143 continue;
3144 }
3145 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3146 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3147 continue;
3148 }
3149 // If the default device for this strategy is on another output mix,
3150 // invalidate all tracks in this strategy to force re connection.
3151 // Otherwise select new device on the output mix.
3152 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003153 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003154 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3155 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3156 }
3157 }
3158 } else {
3159 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3160 setOutputDevice(outputDesc, newDevice, false);
3161 }
3162 }
3163}
3164
3165void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3166{
3167 // remove output routes associated with this uid
3168 SortedVector<routing_strategy> affectedStrategies;
3169 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3170 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3171 if (route->mUid == uid) {
3172 mOutputRoutes.removeItemsAt(i);
3173 if (route->mDeviceDescriptor != 0) {
3174 affectedStrategies.add(getStrategy(route->mStreamType));
3175 }
3176 }
3177 }
3178 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003179 for (const auto& strategy : affectedStrategies) {
3180 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003181 }
3182
3183 // remove input routes associated with this uid
3184 SortedVector<audio_source_t> affectedSources;
3185 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3186 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3187 if (route->mUid == uid) {
3188 mInputRoutes.removeItemsAt(i);
3189 if (route->mDeviceDescriptor != 0) {
3190 affectedSources.add(route->mSource);
3191 }
3192 }
3193 }
3194 // reroute inputs if necessary
3195 SortedVector<audio_io_handle_t> inputsToClose;
3196 for (size_t i = 0; i < mInputs.size(); i++) {
3197 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003198 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003199 inputsToClose.add(inputDesc->mIoHandle);
3200 }
3201 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003202 for (const auto& input : inputsToClose) {
3203 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003204 }
3205}
3206
Eric Laurentd60560a2015-04-10 11:31:20 -07003207void AudioPolicyManager::clearAudioSources(uid_t uid)
3208{
3209 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3210 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3211 if (sourceDesc->mUid == uid) {
3212 stopAudioSource(mAudioSources.keyAt(i));
3213 }
3214 }
3215}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003216
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003217status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3218 audio_io_handle_t *ioHandle,
3219 audio_devices_t *device)
3220{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003221 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3222 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003223 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003224
François Gaffiedf372692015-03-19 10:43:27 +01003225 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003226}
3227
Eric Laurentd60560a2015-04-10 11:31:20 -07003228status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3229 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003230 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003231 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003232{
Eric Laurentd60560a2015-04-10 11:31:20 -07003233 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3234 if (source == NULL || attributes == NULL || handle == NULL) {
3235 return BAD_VALUE;
3236 }
3237
Glenn Kasten559d4392016-03-29 13:42:57 -07003238 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003239
3240 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3241 source->type != AUDIO_PORT_TYPE_DEVICE) {
3242 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3243 return INVALID_OPERATION;
3244 }
3245
3246 sp<DeviceDescriptor> srcDeviceDesc =
3247 mAvailableInputDevices.getDevice(source->ext.device.type,
3248 String8(source->ext.device.address));
3249 if (srcDeviceDesc == 0) {
3250 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3251 return BAD_VALUE;
3252 }
3253 sp<AudioSourceDescriptor> sourceDesc =
3254 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3255
3256 struct audio_patch dummyPatch;
3257 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3258 sourceDesc->mPatchDesc = patchDesc;
3259
3260 status_t status = connectAudioSource(sourceDesc);
3261 if (status == NO_ERROR) {
3262 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3263 *handle = sourceDesc->getHandle();
3264 }
3265 return status;
3266}
3267
3268status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3269{
3270 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3271
3272 // make sure we only have one patch per source.
3273 disconnectAudioSource(sourceDesc);
3274
3275 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003276 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003277 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3278
3279 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3280 sp<DeviceDescriptor> sinkDeviceDesc =
3281 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3282
3283 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3284 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3285
3286 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3287 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003288 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003289 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3290 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3291 // create patch between src device and output device
3292 // create Hwoutput and add to mHwOutputs
3293 } else {
3294 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3295 audio_io_handle_t output =
3296 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3297 if (output == AUDIO_IO_HANDLE_NONE) {
3298 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3299 return INVALID_OPERATION;
3300 }
3301 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3302 if (outputDesc->isDuplicated()) {
3303 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3304 return INVALID_OPERATION;
3305 }
3306 // create a special patch with no sink and two sources:
3307 // - the second source indicates to PatchPanel through which output mix this patch should
3308 // be connected as well as the stream type for volume control
3309 // - the sink is defined by whatever output device is currently selected for the output
3310 // though which this patch is routed.
3311 patch->num_sinks = 0;
3312 patch->num_sources = 2;
3313 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3314 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3315 patch->sources[1].ext.mix.usecase.stream = stream;
3316 status_t status = mpClientInterface->createAudioPatch(patch,
3317 &afPatchHandle,
3318 0);
3319 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3320 status, afPatchHandle);
3321 if (status != NO_ERROR) {
3322 ALOGW("%s patch panel could not connect device patch, error %d",
3323 __FUNCTION__, status);
3324 return INVALID_OPERATION;
3325 }
3326 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003327 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003328
3329 if (status != NO_ERROR) {
3330 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3331 return status;
3332 }
3333 sourceDesc->mSwOutput = outputDesc;
3334 if (delayMs != 0) {
3335 usleep(delayMs * 1000);
3336 }
3337 }
3338
3339 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3340 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3341
3342 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003343}
3344
Glenn Kasten559d4392016-03-29 13:42:57 -07003345status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003346{
Eric Laurentd60560a2015-04-10 11:31:20 -07003347 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3348 ALOGV("%s handle %d", __FUNCTION__, handle);
3349 if (sourceDesc == 0) {
3350 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3351 return BAD_VALUE;
3352 }
3353 status_t status = disconnectAudioSource(sourceDesc);
3354
3355 mAudioSources.removeItem(handle);
3356 return status;
3357}
3358
Andy Hung2ddee192015-12-18 17:34:44 -08003359status_t AudioPolicyManager::setMasterMono(bool mono)
3360{
3361 if (mMasterMono == mono) {
3362 return NO_ERROR;
3363 }
3364 mMasterMono = mono;
3365 // if enabling mono we close all offloaded devices, which will invalidate the
3366 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3367 // for recreating the new AudioTrack as non-offloaded PCM.
3368 //
3369 // If disabling mono, we leave all tracks as is: we don't know which clients
3370 // and tracks are able to be recreated as offloaded. The next "song" should
3371 // play back offloaded.
3372 if (mMasterMono) {
3373 Vector<audio_io_handle_t> offloaded;
3374 for (size_t i = 0; i < mOutputs.size(); ++i) {
3375 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3376 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3377 offloaded.push(desc->mIoHandle);
3378 }
3379 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003380 for (const auto& handle : offloaded) {
3381 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003382 }
3383 }
3384 // update master mono for all remaining outputs
3385 for (size_t i = 0; i < mOutputs.size(); ++i) {
3386 updateMono(mOutputs.keyAt(i));
3387 }
3388 return NO_ERROR;
3389}
3390
3391status_t AudioPolicyManager::getMasterMono(bool *mono)
3392{
3393 *mono = mMasterMono;
3394 return NO_ERROR;
3395}
3396
Eric Laurentac9cef52017-06-09 15:46:26 -07003397float AudioPolicyManager::getStreamVolumeDB(
3398 audio_stream_type_t stream, int index, audio_devices_t device)
3399{
3400 return computeVolume(stream, index, device);
3401}
3402
Eric Laurentd60560a2015-04-10 11:31:20 -07003403status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3404{
3405 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3406
3407 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3408 if (patchDesc == 0) {
3409 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3410 sourceDesc->mPatchDesc->mHandle);
3411 return BAD_VALUE;
3412 }
3413 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3414
Eric Laurent28d09f02016-03-08 10:43:05 -08003415 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003416 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3417 if (swOutputDesc != 0) {
3418 stopSource(swOutputDesc, stream, false);
3419 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3420 } else {
3421 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3422 if (hwOutputDesc != 0) {
3423 // release patch between src device and output device
3424 // close Hwoutput and remove from mHwOutputs
3425 } else {
3426 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3427 }
3428 }
3429 return NO_ERROR;
3430}
3431
3432sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3433 audio_io_handle_t output, routing_strategy strategy)
3434{
3435 sp<AudioSourceDescriptor> source;
3436 for (size_t i = 0; i < mAudioSources.size(); i++) {
3437 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3438 routing_strategy sourceStrategy =
3439 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3440 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3441 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3442 source = sourceDesc;
3443 break;
3444 }
3445 }
3446 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003447}
3448
Eric Laurente552edb2014-03-10 17:42:56 -07003449// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003450// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003451// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003452uint32_t AudioPolicyManager::nextAudioPortGeneration()
3453{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003454 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003455}
3456
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003457#ifdef USE_XML_AUDIO_POLICY_CONF
3458// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3459static const char *kConfigLocationList[] =
3460 {"/odm/etc", "/vendor/etc", "/system/etc"};
3461static const int kConfigLocationListSize =
3462 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3463
3464static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3465 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3466 status_t ret;
3467
3468 for (int i = 0; i < kConfigLocationListSize; i++) {
3469 PolicySerializer serializer;
3470 snprintf(audioPolicyXmlConfigFile,
3471 sizeof(audioPolicyXmlConfigFile),
3472 "%s/%s",
3473 kConfigLocationList[i],
3474 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3475 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3476 if (ret == NO_ERROR) {
3477 break;
3478 }
3479 }
3480 return ret;
3481}
3482#endif
3483
Eric Laurente0720872014-03-11 09:30:41 -07003484AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003485 :
Eric Laurente552edb2014-03-10 17:42:56 -07003486 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003487 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003488 mAudioPortGeneration(1),
3489 mBeaconMuteRefCount(0),
3490 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003491 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003492 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003493 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003494 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3495 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003496{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003497 mUidCached = getuid();
3498 mpClientInterface = clientInterface;
3499
3500 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3501 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3502 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3503 bool speakerDrcEnabled = false;
3504
3505#ifdef USE_XML_AUDIO_POLICY_CONF
3506 mVolumeCurves = new VolumeCurvesCollection();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003507 AudioPolicyConfig config(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
François Gaffied1ab2bd2015-12-02 18:20:06 +01003508 mDefaultOutputDevice, speakerDrcEnabled,
3509 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003510 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003511#else
3512 mVolumeCurves = new StreamDescriptorCollection();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003513 AudioPolicyConfig config(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
François Gaffied1ab2bd2015-12-02 18:20:06 +01003514 mDefaultOutputDevice, speakerDrcEnabled);
3515 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3516 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3517#endif
3518 ALOGE("could not load audio policy configuration file, setting defaults");
3519 config.setDefault();
3520 }
3521 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3522 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3523
3524 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003525 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3526 if (!engineInstance) {
3527 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3528 return;
3529 }
3530 // Retrieve the Policy Manager Interface
3531 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3532 if (mEngine == NULL) {
3533 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3534 return;
3535 }
3536 mEngine->setObserver(this);
3537 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003538 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003539 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3540
Eric Laurent3a4311c2014-03-17 12:00:47 -07003541 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003542 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003543 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3544 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003545 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003546 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003547 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3548 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003549 continue;
3550 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003551 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003552 // open all output streams needed to access attached devices
3553 // except for direct output streams that are only opened when they are actually
3554 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003555 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003556 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003557 if (!outProfile->canOpenNewIo()) {
3558 ALOGE("Invalid Output profile max open count %u for profile %s",
3559 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3560 continue;
3561 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003562 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003563 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003564 continue;
3565 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003566 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003567 mTtsOutputAvailable = true;
3568 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003569
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003570 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003571 continue;
3572 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003573 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003574 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3575 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003576 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003577 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003578 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003579 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003580 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003581 if ((profileType & outputDeviceTypes) == 0) {
3582 continue;
3583 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003584 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3585 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003586 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3587 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3588 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3589 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003590 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003591 status_t status = outputDesc->open(nullptr, profileType, address,
3592 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003593
3594 if (status != NO_ERROR) {
3595 ALOGW("Cannot open output stream for device %08x on hw module %s",
3596 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003597 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003598 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003599 for (const auto& dev : supportedDevices) {
3600 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003601 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003602 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003603 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003604 }
3605 }
3606 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003607 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003608 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003609 }
3610 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003611 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003612 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003613 true,
3614 0,
3615 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003616 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003617 }
Eric Laurente552edb2014-03-10 17:42:56 -07003618 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003619 // open input streams needed to access attached devices to validate
3620 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003621 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003622 if (!inProfile->canOpenNewIo()) {
3623 ALOGE("Invalid Input profile max open count %u for profile %s",
3624 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3625 continue;
3626 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003627 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003628 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003629 continue;
3630 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003631 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003632 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003633 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3634
Eric Laurentd78f1532014-09-16 16:38:20 -07003635 if ((profileType & inputDeviceTypes) == 0) {
3636 continue;
3637 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003638 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003639 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003640
Eric Laurent53b810e2017-12-10 17:25:10 -08003641 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3642 // the inputs vector must be of size >= 1, but we don't want to crash here
3643 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3644 : String8("");
3645 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3646 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3647
Eric Laurentd78f1532014-09-16 16:38:20 -07003648 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003649 status_t status = inputDesc->open(nullptr,
3650 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003651 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003652 AUDIO_SOURCE_MIC,
3653 AUDIO_INPUT_FLAG_NONE,
3654 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003655
3656 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003657 for (const auto& dev : inProfile->getSupportedDevices()) {
3658 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003659 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003660 if (index >= 0) {
3661 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3662 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003663 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003664 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003665 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003666 }
3667 }
Eric Laurentfe231122017-11-17 17:48:06 -08003668 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003669 } else {
3670 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003671 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003672 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003673 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003674 }
3675 }
3676 // make sure all attached devices have been allocated a unique ID
3677 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003678 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003679 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003680 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3681 continue;
3682 }
François Gaffie2110e042015-03-24 08:41:51 +01003683 // The device is now validated and can be appended to the available devices of the engine
3684 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3685 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003686 i++;
3687 }
3688 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003689 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003690 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003691 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3692 continue;
3693 }
François Gaffie2110e042015-03-24 08:41:51 +01003694 // The device is now validated and can be appended to the available devices of the engine
3695 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3696 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003697 i++;
3698 }
3699 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003700 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003701 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003702 }
Eric Laurente552edb2014-03-10 17:42:56 -07003703
3704 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3705
3706 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -07003707}
3708
Eric Laurente0720872014-03-11 09:30:41 -07003709AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003710{
Eric Laurente552edb2014-03-10 17:42:56 -07003711 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003712 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003713 }
3714 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003715 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003716 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003717 mAvailableOutputDevices.clear();
3718 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003719 mOutputs.clear();
3720 mInputs.clear();
3721 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003722 mHwModulesAll.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003723}
3724
Eric Laurente0720872014-03-11 09:30:41 -07003725status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003726{
Eric Laurent87ffa392015-05-22 10:32:38 -07003727 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003728}
3729
Eric Laurente552edb2014-03-10 17:42:56 -07003730// ---
3731
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003732void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003733{
Eric Laurent1c333e22014-05-20 10:48:17 -07003734 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003735 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003736 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003737 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003738}
3739
François Gaffie53615e22015-03-19 09:24:12 +01003740void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3741{
3742 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07003743 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01003744}
3745
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003746void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003747{
Eric Laurent1c333e22014-05-20 10:48:17 -07003748 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003749 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003750}
Eric Laurente552edb2014-03-10 17:42:56 -07003751
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003752void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003753 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003754 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003755 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003756 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003757 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003758 if (devDesc != 0) {
3759 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3760 desc->mIoHandle, address.string());
3761 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003762 }
3763}
3764
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003765status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003766 audio_policy_dev_state_t state,
3767 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003768 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003769{
François Gaffie53615e22015-03-19 09:24:12 +01003770 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003771 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003772
3773 if (audio_device_is_digital(device)) {
3774 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003775 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003776 }
Eric Laurente552edb2014-03-10 17:42:56 -07003777
Eric Laurent3b73df72014-03-11 09:06:29 -07003778 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003779 // first list already open outputs that can be routed to this device
3780 for (size_t i = 0; i < mOutputs.size(); i++) {
3781 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003782 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003783 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003784 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3785 outputs.add(mOutputs.keyAt(i));
3786 } else {
3787 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003788 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003789 }
Eric Laurente552edb2014-03-10 17:42:56 -07003790 }
3791 }
3792 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003794 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003795 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
3796 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003797 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003798 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003799 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003800 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08003801 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
3802 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08003803 }
Eric Laurente552edb2014-03-10 17:42:56 -07003804 }
3805 }
3806 }
3807
Eric Laurent7b279bb2015-12-14 10:18:23 -08003808 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003809
Eric Laurente552edb2014-03-10 17:42:56 -07003810 if (profiles.isEmpty() && outputs.isEmpty()) {
3811 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3812 return BAD_VALUE;
3813 }
3814
3815 // open outputs for matching profiles if needed. Direct outputs are also opened to
3816 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3817 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003818 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003819
3820 // nothing to do if one output is already opened for this profile
3821 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003822 for (j = 0; j < outputs.size(); j++) {
3823 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003824 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003825 // matching profile: save the sample rates, format and channel masks supported
3826 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003827 if (audio_device_is_digital(device)) {
3828 devDesc->importAudioPort(profile);
3829 }
Eric Laurente552edb2014-03-10 17:42:56 -07003830 break;
3831 }
3832 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003833 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003834 continue;
3835 }
3836
Eric Laurent3974e3b2017-12-07 17:58:43 -08003837 if (!profile->canOpenNewIo()) {
3838 ALOGW("Max Output number %u already opened for this profile %s",
3839 profile->maxOpenCount, profile->getTagName().c_str());
3840 continue;
3841 }
3842
Eric Laurent83efe1c2017-07-09 16:51:08 -07003843 ALOGV("opening output for device %08x with params %s profile %p name %s",
3844 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003845 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003846 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003847 status_t status = desc->open(nullptr, device, address,
3848 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07003849
Eric Laurentfe231122017-11-17 17:48:06 -08003850 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07003851 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003852 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003853 char *param = audio_device_address_to_parameter(device, address);
3854 mpClientInterface->setParameters(output, String8(param));
3855 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003856 }
Phil Burk00eeb322016-03-31 12:41:00 -07003857 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003858 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003859 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08003860 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003861 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003862 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08003863 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08003864 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003865 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3866 profile->pickAudioProfile(
3867 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003868 config.offload_info.sample_rate = config.sample_rate;
3869 config.offload_info.channel_mask = config.channel_mask;
3870 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08003871
3872 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
3873 AUDIO_OUTPUT_FLAG_NONE, &output);
3874 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003875 output = AUDIO_IO_HANDLE_NONE;
3876 }
Eric Laurentd4692962014-05-05 18:13:44 -07003877 }
3878
Eric Laurentcf2c0212014-07-25 16:20:43 -07003879 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003880 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003881 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003882 sp<AudioPolicyMix> policyMix;
3883 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003884 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3885 address.string());
3886 }
François Gaffie036e1e92015-03-19 10:16:24 +01003887 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003888 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003889
Eric Laurent87ffa392015-05-22 10:32:38 -07003890 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3891 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003892 // no duplicated output for direct outputs and
3893 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003894 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003895
Eric Laurentd4692962014-05-05 18:13:44 -07003896 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003897 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003898
Eric Laurentd4692962014-05-05 18:13:44 -07003899 //TODO: configure audio effect output stage here
3900
3901 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003902 duplicatedOutput =
3903 mpClientInterface->openDuplicateOutput(output,
3904 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003905 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003906 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003907 sp<SwAudioOutputDescriptor> dupOutputDesc =
3908 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3909 dupOutputDesc->mOutput1 = mPrimaryOutput;
3910 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003911 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3912 dupOutputDesc->mFormat = desc->mFormat;
3913 dupOutputDesc->mChannelMask = desc->mChannelMask;
3914 dupOutputDesc->mLatency = desc->mLatency;
3915 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003916 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003917 } else {
3918 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003919 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08003920 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01003921 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003922 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003923 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003924 }
Eric Laurente552edb2014-03-10 17:42:56 -07003925 }
3926 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003927 } else {
3928 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003929 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003930 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003931 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003932 profiles.removeAt(profile_index);
3933 profile_index--;
3934 } else {
3935 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003936 // Load digital format info only for digital devices
3937 if (audio_device_is_digital(device)) {
3938 devDesc->importAudioPort(profile);
3939 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003940
François Gaffie53615e22015-03-19 09:24:12 +01003941 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003942 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3943 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003944 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003945 NULL/*patch handle*/, address.string());
3946 }
Eric Laurente552edb2014-03-10 17:42:56 -07003947 ALOGV("checkOutputsForDevice(): adding output %d", output);
3948 }
3949 }
3950
3951 if (profiles.isEmpty()) {
3952 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3953 return BAD_VALUE;
3954 }
Eric Laurentd4692962014-05-05 18:13:44 -07003955 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003956 // check if one opened output is not needed any more after disconnecting one device
3957 for (size_t i = 0; i < mOutputs.size(); i++) {
3958 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003959 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003960 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003961 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003962 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003963 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003964 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003965 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3966 mOutputs.keyAt(i));
3967 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003968 }
Eric Laurente552edb2014-03-10 17:42:56 -07003969 }
3970 }
Eric Laurentd4692962014-05-05 18:13:44 -07003971 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003972 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003973 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
3974 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003975 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003976 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08003977 "clearing direct output profile %zu on module %s",
3978 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01003979 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003980 }
3981 }
3982 }
3983 }
3984 return NO_ERROR;
3985}
3986
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003987status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003988 audio_policy_dev_state_t state,
3989 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003990 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003991{
Paul McLean9080a4c2015-06-18 08:24:02 -07003992 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003993 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003994
3995 if (audio_device_is_digital(device)) {
3996 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003997 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003998 }
3999
Eric Laurentd4692962014-05-05 18:13:44 -07004000 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4001 // first list already open inputs that can be routed to this device
4002 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4003 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004004 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004005 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4006 inputs.add(mInputs.keyAt(input_index));
4007 }
4008 }
4009
4010 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004011 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004012 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004013 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004014 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004015 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004016 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004017
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004019 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004020 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004021 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004022 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4023 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004024 }
Eric Laurentd4692962014-05-05 18:13:44 -07004025 }
4026 }
4027 }
4028
4029 if (profiles.isEmpty() && inputs.isEmpty()) {
4030 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4031 return BAD_VALUE;
4032 }
4033
4034 // open inputs for matching profiles if needed. Direct inputs are also opened to
4035 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4036 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4037
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004039
Eric Laurentd4692962014-05-05 18:13:44 -07004040 // nothing to do if one input is already opened for this profile
4041 size_t input_index;
4042 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4043 desc = mInputs.valueAt(input_index);
4044 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004045 if (audio_device_is_digital(device)) {
4046 devDesc->importAudioPort(profile);
4047 }
Eric Laurentd4692962014-05-05 18:13:44 -07004048 break;
4049 }
4050 }
4051 if (input_index != mInputs.size()) {
4052 continue;
4053 }
4054
Eric Laurent3974e3b2017-12-07 17:58:43 -08004055 if (!profile->canOpenNewIo()) {
4056 ALOGW("Max Input number %u already opened for this profile %s",
4057 profile->maxOpenCount, profile->getTagName().c_str());
4058 continue;
4059 }
4060
Eric Laurentfe231122017-11-17 17:48:06 -08004061 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004062 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004063 status_t status = desc->open(nullptr,
4064 device,
4065 address,
4066 AUDIO_SOURCE_MIC,
4067 AUDIO_INPUT_FLAG_NONE,
4068 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004069
Eric Laurentcf2c0212014-07-25 16:20:43 -07004070 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004071 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004072 char *param = audio_device_address_to_parameter(device, address);
4073 mpClientInterface->setParameters(input, String8(param));
4074 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004075 }
Phil Burk00eeb322016-03-31 12:41:00 -07004076 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004077 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004078 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004079 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004080 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004081 }
4082
4083 if (input != 0) {
4084 addInput(input, desc);
4085 }
4086 } // endif input != 0
4087
Eric Laurentcf2c0212014-07-25 16:20:43 -07004088 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004089 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004090 profiles.removeAt(profile_index);
4091 profile_index--;
4092 } else {
4093 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004094 if (audio_device_is_digital(device)) {
4095 devDesc->importAudioPort(profile);
4096 }
Eric Laurentd4692962014-05-05 18:13:44 -07004097 ALOGV("checkInputsForDevice(): adding input %d", input);
4098 }
4099 } // end scan profiles
4100
4101 if (profiles.isEmpty()) {
4102 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4103 return BAD_VALUE;
4104 }
4105 } else {
4106 // Disconnect
4107 // check if one opened input is not needed any more after disconnecting one device
4108 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4109 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004110 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004111 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4112 mInputs.keyAt(input_index));
4113 inputs.add(mInputs.keyAt(input_index));
4114 }
4115 }
4116 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004117 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004118 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004119 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004120 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004121 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004122 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004123 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4124 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004125 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004126 }
4127 }
4128 }
4129 } // end disconnect
4130
4131 return NO_ERROR;
4132}
4133
4134
Eric Laurente0720872014-03-11 09:30:41 -07004135void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004136{
4137 ALOGV("closeOutput(%d)", output);
4138
Eric Laurentc75307b2015-03-17 15:29:32 -07004139 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004140 if (outputDesc == NULL) {
4141 ALOGW("closeOutput() unknown output %d", output);
4142 return;
4143 }
François Gaffie036e1e92015-03-19 10:16:24 +01004144 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004145
Eric Laurente552edb2014-03-10 17:42:56 -07004146 // look for duplicated outputs connected to the output being removed.
4147 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004148 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004149 if (dupOutputDesc->isDuplicated() &&
4150 (dupOutputDesc->mOutput1 == outputDesc ||
4151 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004152 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004153 if (dupOutputDesc->mOutput1 == outputDesc) {
4154 outputDesc2 = dupOutputDesc->mOutput2;
4155 } else {
4156 outputDesc2 = dupOutputDesc->mOutput1;
4157 }
4158 // As all active tracks on duplicated output will be deleted,
4159 // and as they were also referenced on the other output, the reference
4160 // count for their stream type must be adjusted accordingly on
4161 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004162 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004163 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004164 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004165 }
4166 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4167 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4168
4169 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004170 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004171 }
4172 }
4173
Eric Laurent05b90f82014-08-27 15:32:29 -07004174 nextAudioPortGeneration();
4175
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004176 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004177 if (index >= 0) {
4178 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004179 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004180 mAudioPatches.removeItemsAt(index);
4181 mpClientInterface->onAudioPatchListUpdate();
4182 }
4183
Eric Laurentfe231122017-11-17 17:48:06 -08004184 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004185
François Gaffie53615e22015-03-19 09:24:12 +01004186 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004187 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004188}
4189
4190void AudioPolicyManager::closeInput(audio_io_handle_t input)
4191{
4192 ALOGV("closeInput(%d)", input);
4193
4194 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4195 if (inputDesc == NULL) {
4196 ALOGW("closeInput() unknown input %d", input);
4197 return;
4198 }
4199
Eric Laurent6a94d692014-05-20 11:18:06 -07004200 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004201
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004202 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004203 if (index >= 0) {
4204 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004205 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004206 mAudioPatches.removeItemsAt(index);
4207 mpClientInterface->onAudioPatchListUpdate();
4208 }
4209
Eric Laurentfe231122017-11-17 17:48:06 -08004210 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004211 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004212}
4213
Eric Laurentc75307b2015-03-17 15:29:32 -07004214SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4215 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004216 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004217{
4218 SortedVector<audio_io_handle_t> outputs;
4219
4220 ALOGVV("getOutputsForDevice() device %04x", device);
4221 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004222 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004223 i, openOutputs.valueAt(i)->isDuplicated(),
4224 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004225 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4226 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4227 outputs.add(openOutputs.keyAt(i));
4228 }
4229 }
4230 return outputs;
4231}
4232
Eric Laurente0720872014-03-11 09:30:41 -07004233bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004234 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004235{
4236 if (outputs1.size() != outputs2.size()) {
4237 return false;
4238 }
4239 for (size_t i = 0; i < outputs1.size(); i++) {
4240 if (outputs1[i] != outputs2[i]) {
4241 return false;
4242 }
4243 }
4244 return true;
4245}
4246
Eric Laurente0720872014-03-11 09:30:41 -07004247void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004248{
4249 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4250 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4251 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4252 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4253
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004254 // also take into account external policy-related changes: add all outputs which are
4255 // associated with policies in the "before" and "after" output vectors
4256 ALOGVV("checkOutputForStrategy(): policy related outputs");
4257 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004258 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004259 if (desc != 0 && desc->mPolicyMix != NULL) {
4260 srcOutputs.add(desc->mIoHandle);
4261 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4262 }
4263 }
4264 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004265 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004266 if (desc != 0 && desc->mPolicyMix != NULL) {
4267 dstOutputs.add(desc->mIoHandle);
4268 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4269 }
4270 }
4271
Eric Laurente552edb2014-03-10 17:42:56 -07004272 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4273 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4274 strategy, srcOutputs[0], dstOutputs[0]);
4275 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004276 for (audio_io_handle_t srcOut : srcOutputs) {
4277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOut);
François Gaffiead3183e2015-03-18 16:55:35 +01004278 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004279 setStrategyMute(strategy, true, desc);
4280 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004281 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004282 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004283 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004284 if (source != 0){
4285 connectAudioSource(source);
4286 }
Eric Laurente552edb2014-03-10 17:42:56 -07004287 }
4288
4289 // Move effects associated to this strategy from previous output to new output
4290 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004291 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004292 }
4293 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004294 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004295 if (getStrategy((audio_stream_type_t)i) == strategy) {
4296 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004297 }
4298 }
4299 }
4300}
4301
Eric Laurente0720872014-03-11 09:30:41 -07004302void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004303{
François Gaffie2110e042015-03-24 08:41:51 +01004304 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004305 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004306 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004307 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004308 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004309 checkOutputForStrategy(STRATEGY_SONIFICATION);
4310 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004311 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004312 checkOutputForStrategy(STRATEGY_MEDIA);
4313 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004314 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004315}
4316
Eric Laurente0720872014-03-11 09:30:41 -07004317void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004318{
François Gaffie53615e22015-03-19 09:24:12 +01004319 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004320 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004321 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004322 return;
4323 }
4324
Eric Laurent3a4311c2014-03-17 12:00:47 -07004325 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004326 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4327 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4328 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004329
4330 // if suspended, restore A2DP output if:
4331 // ((SCO device is NOT connected) ||
4332 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4333 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004334 //
Eric Laurentf732e072016-08-03 19:30:28 -07004335 // if not suspended, suspend A2DP output if:
4336 // (SCO device is connected) &&
4337 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4338 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004339 //
4340 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004341 if (!isScoConnected ||
4342 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4343 AUDIO_POLICY_FORCE_BT_SCO) &&
4344 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4345 AUDIO_POLICY_FORCE_BT_SCO) &&
4346 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004347 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004348
4349 mpClientInterface->restoreOutput(a2dpOutput);
4350 mA2dpSuspended = false;
4351 }
4352 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004353 if (isScoConnected &&
4354 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4355 AUDIO_POLICY_FORCE_BT_SCO) ||
4356 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4357 AUDIO_POLICY_FORCE_BT_SCO) ||
4358 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004359 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004360
4361 mpClientInterface->suspendOutput(a2dpOutput);
4362 mA2dpSuspended = true;
4363 }
4364 }
4365}
4366
Eric Laurentc75307b2015-03-17 15:29:32 -07004367audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4368 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004369{
4370 audio_devices_t device = AUDIO_DEVICE_NONE;
4371
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004372 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 if (index >= 0) {
4374 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4375 if (patchDesc->mUid != mUidCached) {
4376 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004377 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004378 return outputDesc->device();
4379 }
4380 }
4381
Eric Laurente552edb2014-03-10 17:42:56 -07004382 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004383 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004384 // use device for strategy enforced audible
4385 // 2: we are in call or the strategy phone is active on the output:
4386 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004387 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004388 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004389 // 4: the strategy for enforced audible is active but not enforced on the output:
4390 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004391 // 5: the strategy accessibility is active on the output:
4392 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004393 // 6: the strategy "respectful" sonification is active on the output:
4394 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004395 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004396 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004397 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004398 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004399 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004400 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004401 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004402 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004403 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4404 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004405 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004406 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004407 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004408 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004409 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4410 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004411 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4412 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004413 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004414 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004415 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004416 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004417 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004418 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004419 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004420 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004421 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004422 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004423 }
4424
Eric Laurent1c333e22014-05-20 10:48:17 -07004425 ALOGV("getNewOutputDevice() selected device %x", device);
4426 return device;
4427}
4428
Eric Laurentfb66dd92016-01-28 18:32:03 -08004429audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004430{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004431 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004432
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004433 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 if (index >= 0) {
4435 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4436 if (patchDesc->mUid != mUidCached) {
4437 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004438 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004439 return inputDesc->mDevice;
4440 }
4441 }
4442
Eric Laurentfb66dd92016-01-28 18:32:03 -08004443 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4444 if (isInCall()) {
4445 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4446 } else if (source != AUDIO_SOURCE_DEFAULT) {
4447 device = getDeviceAndMixForInputSource(source);
4448 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004449
Eric Laurente552edb2014-03-10 17:42:56 -07004450 return device;
4451}
4452
Eric Laurent794fde22016-03-11 09:50:45 -08004453bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4454 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004455 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004456}
4457
Eric Laurente0720872014-03-11 09:30:41 -07004458uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004459 return (uint32_t)getStrategy(stream);
4460}
4461
Eric Laurente0720872014-03-11 09:30:41 -07004462audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004463 // By checking the range of stream before calling getStrategy, we avoid
4464 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4465 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004466 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004467 return AUDIO_DEVICE_NONE;
4468 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004469 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004470 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4471 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004472 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 }
Eric Laurent794fde22016-03-11 09:50:45 -08004474 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004475 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004476 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004477 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4478 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004479 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004480 curDevices |= outputDesc->device();
4481 }
4482 }
4483 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004484 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004485
4486 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4487 and doesn't really need to.*/
4488 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4489 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4490 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4491 }
Eric Laurente552edb2014-03-10 17:42:56 -07004492 return devices;
4493}
4494
François Gaffie2110e042015-03-24 08:41:51 +01004495routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4496{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004497 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004498 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004499}
4500
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004501uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4502 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004503 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4504 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4505 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004506 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4507 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4508 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004509 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004510 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004511}
4512
Eric Laurente0720872014-03-11 09:30:41 -07004513void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004514 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004515 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004516 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4517 updateDevicesAndOutputs();
4518 break;
4519 default:
4520 break;
4521 }
4522}
4523
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004524uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004525
4526 // skip beacon mute management if a dedicated TTS output is available
4527 if (mTtsOutputAvailable) {
4528 return 0;
4529 }
4530
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004531 switch(event) {
4532 case STARTING_OUTPUT:
4533 mBeaconMuteRefCount++;
4534 break;
4535 case STOPPING_OUTPUT:
4536 if (mBeaconMuteRefCount > 0) {
4537 mBeaconMuteRefCount--;
4538 }
4539 break;
4540 case STARTING_BEACON:
4541 mBeaconPlayingRefCount++;
4542 break;
4543 case STOPPING_BEACON:
4544 if (mBeaconPlayingRefCount > 0) {
4545 mBeaconPlayingRefCount--;
4546 }
4547 break;
4548 }
4549
4550 if (mBeaconMuteRefCount > 0) {
4551 // any playback causes beacon to be muted
4552 return setBeaconMute(true);
4553 } else {
4554 // no other playback: unmute when beacon starts playing, mute when it stops
4555 return setBeaconMute(mBeaconPlayingRefCount == 0);
4556 }
4557}
4558
4559uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4560 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4561 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4562 // keep track of muted state to avoid repeating mute/unmute operations
4563 if (mBeaconMuted != mute) {
4564 // mute/unmute AUDIO_STREAM_TTS on all outputs
4565 ALOGV("\t muting %d", mute);
4566 uint32_t maxLatency = 0;
4567 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004569 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004570 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004571 0 /*delay*/, AUDIO_DEVICE_NONE);
4572 const uint32_t latency = desc->latency() * 2;
4573 if (latency > maxLatency) {
4574 maxLatency = latency;
4575 }
4576 }
4577 mBeaconMuted = mute;
4578 return maxLatency;
4579 }
4580 return 0;
4581}
4582
Eric Laurente0720872014-03-11 09:30:41 -07004583audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004584 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004585{
Paul McLeanaa981192015-03-21 09:55:15 -07004586 // Routing
4587 // see if we have an explicit route
4588 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4589 // (getStrategy(stream)).
4590 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004591 // and activity count is non-zero and the device in the route descriptor is available
4592 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004593 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4594 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004595 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004596 if ((routeStrategy == strategy) && route->isActive() &&
4597 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004598 return route->mDeviceDescriptor->type();
4599 }
4600 }
4601
Eric Laurente552edb2014-03-10 17:42:56 -07004602 if (fromCache) {
4603 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4604 strategy, mDeviceForStrategy[strategy]);
4605 return mDeviceForStrategy[strategy];
4606 }
François Gaffie2110e042015-03-24 08:41:51 +01004607 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004608}
4609
Eric Laurente0720872014-03-11 09:30:41 -07004610void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004611{
4612 for (int i = 0; i < NUM_STRATEGIES; i++) {
4613 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4614 }
4615 mPreviousOutputs = mOutputs;
4616}
4617
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004618uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004619 audio_devices_t prevDevice,
4620 uint32_t delayMs)
4621{
4622 // mute/unmute strategies using an incompatible device combination
4623 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4624 // if unmuting, unmute only after the specified delay
4625 if (outputDesc->isDuplicated()) {
4626 return 0;
4627 }
4628
4629 uint32_t muteWaitMs = 0;
4630 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004631 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004632
4633 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4634 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004635 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004636 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4637 bool doMute = false;
4638
4639 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4640 doMute = true;
4641 outputDesc->mStrategyMutedByDevice[i] = true;
4642 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4643 doMute = true;
4644 outputDesc->mStrategyMutedByDevice[i] = false;
4645 }
Eric Laurent99401132014-05-07 19:48:15 -07004646 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004648 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004649 // skip output if it does not share any device with current output
4650 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4651 == AUDIO_DEVICE_NONE) {
4652 continue;
4653 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004654 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004655 mute ? "muting" : "unmuting", i, curDevice);
4656 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004657 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004658 if (mute) {
4659 // FIXME: should not need to double latency if volume could be applied
4660 // immediately by the audioflinger mixer. We must account for the delay
4661 // between now and the next time the audioflinger thread for this output
4662 // will process a buffer (which corresponds to one buffer size,
4663 // usually 1/2 or 1/4 of the latency).
4664 if (muteWaitMs < desc->latency() * 2) {
4665 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004666 }
4667 }
4668 }
4669 }
4670 }
4671 }
4672
Eric Laurent99401132014-05-07 19:48:15 -07004673 // temporary mute output if device selection changes to avoid volume bursts due to
4674 // different per device volumes
4675 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004676 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4677 // temporary mute duration is conservatively set to 4 times the reported latency
4678 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4679 if (muteWaitMs < tempMuteWaitMs) {
4680 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004681 }
Eric Laurentdc462862016-07-19 12:29:53 -07004682
Eric Laurent99401132014-05-07 19:48:15 -07004683 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004684 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004685 // make sure that we do not start the temporary mute period too early in case of
4686 // delayed device change
4687 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004688 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004689 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004690 }
4691 }
4692 }
4693
Eric Laurente552edb2014-03-10 17:42:56 -07004694 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4695 if (muteWaitMs > delayMs) {
4696 muteWaitMs -= delayMs;
4697 usleep(muteWaitMs * 1000);
4698 return muteWaitMs;
4699 }
4700 return 0;
4701}
4702
Eric Laurentc75307b2015-03-17 15:29:32 -07004703uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004704 audio_devices_t device,
4705 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004707 audio_patch_handle_t *patchHandle,
Andy Hung7c7124e2017-10-20 12:03:34 -07004708 const char *address,
4709 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07004710{
Eric Laurentc75307b2015-03-17 15:29:32 -07004711 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 AudioParameter param;
4713 uint32_t muteWaitMs;
4714
4715 if (outputDesc->isDuplicated()) {
Andy Hung7c7124e2017-10-20 12:03:34 -07004716 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
4717 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
4718 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
4719 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07004720 return muteWaitMs;
4721 }
4722 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4723 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 if ((device != AUDIO_DEVICE_NONE) &&
Andy Hung7c7124e2017-10-20 12:03:34 -07004725 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004726 return 0;
4727 }
4728
4729 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004730 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004731
4732 audio_devices_t prevDevice = outputDesc->mDevice;
4733
Paul McLeanaa981192015-03-21 09:55:15 -07004734 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004735
4736 if (device != AUDIO_DEVICE_NONE) {
4737 outputDesc->mDevice = device;
4738 }
Andy Hung7c7124e2017-10-20 12:03:34 -07004739
4740 // if the outputs are not materially active, there is no need to mute.
4741 if (requiresMuteCheck) {
4742 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4743 } else {
4744 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
4745 muteWaitMs = 0;
4746 }
Eric Laurente552edb2014-03-10 17:42:56 -07004747
4748 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004749 // the requested device is AUDIO_DEVICE_NONE
4750 // OR the requested device is the same as current device
4751 // AND force is not specified
4752 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004753 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004754 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4755 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004756 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004757 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004758 return muteWaitMs;
4759 }
4760
4761 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004762
Eric Laurente552edb2014-03-10 17:42:56 -07004763 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004764 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004765 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004766 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004767 DeviceVector deviceList;
4768 if ((address == NULL) || (strlen(address) == 0)) {
4769 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4770 } else {
4771 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4772 }
4773
Eric Laurent1c333e22014-05-20 10:48:17 -07004774 if (!deviceList.isEmpty()) {
4775 struct audio_patch patch;
4776 outputDesc->toAudioPortConfig(&patch.sources[0]);
4777 patch.num_sources = 1;
4778 patch.num_sinks = 0;
4779 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4780 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004781 patch.num_sinks++;
4782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 ssize_t index;
4784 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4785 index = mAudioPatches.indexOfKey(*patchHandle);
4786 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004787 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 }
4789 sp< AudioPatch> patchDesc;
4790 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4791 if (index >= 0) {
4792 patchDesc = mAudioPatches.valueAt(index);
4793 afPatchHandle = patchDesc->mAfPatchHandle;
4794 }
4795
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 &afPatchHandle,
4798 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004799 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4800 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004802 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004804 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 addAudioPatch(patchDesc->mHandle, patchDesc);
4806 } else {
4807 patchDesc->mPatch = patch;
4808 }
4809 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004810 if (patchHandle) {
4811 *patchHandle = patchDesc->mHandle;
4812 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004813 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004815 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004816 }
4817 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004818
4819 // inform all input as well
4820 for (size_t i = 0; i < mInputs.size(); i++) {
4821 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004822 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004823 AudioParameter inputCmd = AudioParameter();
4824 ALOGV("%s: inform input %d of device:%d", __func__,
4825 inputDescriptor->mIoHandle, device);
4826 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4827 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4828 inputCmd.toString(),
4829 delayMs);
4830 }
4831 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004832 }
Eric Laurente552edb2014-03-10 17:42:56 -07004833
4834 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004835 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004836
4837 return muteWaitMs;
4838}
4839
Eric Laurentc75307b2015-03-17 15:29:32 -07004840status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 int delayMs,
4842 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004843{
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 ssize_t index;
4845 if (patchHandle) {
4846 index = mAudioPatches.indexOfKey(*patchHandle);
4847 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004848 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 }
4850 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004851 return INVALID_OPERATION;
4852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4854 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004855 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004856 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 removeAudioPatch(patchDesc->mHandle);
4858 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004859 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004860 return status;
4861}
4862
4863status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4864 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 bool force,
4866 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004867{
4868 status_t status = NO_ERROR;
4869
Eric Laurent1f2f2232014-06-02 12:01:23 -07004870 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004871 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4872 inputDesc->mDevice = device;
4873
4874 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4875 if (!deviceList.isEmpty()) {
4876 struct audio_patch patch;
4877 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004878 // AUDIO_SOURCE_HOTWORD is for internal use only:
4879 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004880 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004881 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004882 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4883 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004884 patch.num_sinks = 1;
4885 //only one input device for now
4886 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004887 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004888 ssize_t index;
4889 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4890 index = mAudioPatches.indexOfKey(*patchHandle);
4891 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004892 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004893 }
4894 sp< AudioPatch> patchDesc;
4895 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4896 if (index >= 0) {
4897 patchDesc = mAudioPatches.valueAt(index);
4898 afPatchHandle = patchDesc->mAfPatchHandle;
4899 }
4900
Eric Laurent1c333e22014-05-20 10:48:17 -07004901 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004902 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 0);
4904 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004906 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004908 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 addAudioPatch(patchDesc->mHandle, patchDesc);
4910 } else {
4911 patchDesc->mPatch = patch;
4912 }
4913 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 if (patchHandle) {
4915 *patchHandle = patchDesc->mHandle;
4916 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004917 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004919 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004920 }
4921 }
4922 }
4923 return status;
4924}
4925
Eric Laurent6a94d692014-05-20 11:18:06 -07004926status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4927 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004928{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004929 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 ssize_t index;
4931 if (patchHandle) {
4932 index = mAudioPatches.indexOfKey(*patchHandle);
4933 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004934 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 }
4936 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004937 return INVALID_OPERATION;
4938 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4940 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004941 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004942 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 removeAudioPatch(patchDesc->mHandle);
4944 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004945 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004946 return status;
4947}
4948
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004949sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004950 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004951 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004952 audio_format_t& format,
4953 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004954 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004955{
4956 // Choose an input profile based on the requested capture parameters: select the first available
4957 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004958 //
4959 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4960 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004961
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004962 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004963 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004964 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004965 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004966 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004967 format,
4968 &format /*updatedFormat*/,
4969 channelMask,
4970 &channelMask /*updatedChannelMask*/,
4971 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004972
Eric Laurente552edb2014-03-10 17:42:56 -07004973 return profile;
4974 }
4975 }
4976 }
4977 return NULL;
4978}
4979
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004980
4981audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004982 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004983{
François Gaffie036e1e92015-03-19 10:16:24 +01004984 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4985 audio_devices_t selectedDeviceFromMix =
4986 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004987
François Gaffie036e1e92015-03-19 10:16:24 +01004988 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4989 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004990 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004991 return getDeviceForInputSource(inputSource);
4992}
4993
4994audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4995{
Eric Laurentad2e7b92017-09-14 20:06:42 -07004996 // Routing
4997 // Scan the whole RouteMap to see if we have an explicit route:
4998 // if the input source in the RouteMap is the same as the argument above,
4999 // and activity count is non-zero and the device in the route descriptor is available
5000 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005001 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5002 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005003 if ((inputSource == route->mSource) && route->isActive() &&
5004 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005005 return route->mDeviceDescriptor->type();
5006 }
5007 }
5008
5009 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005010}
5011
Eric Laurente0720872014-03-11 09:30:41 -07005012float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005013 int index,
5014 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005015{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005016 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005017
5018 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5019 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5020 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5021 // the ringtone volume
5022 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5023 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5024 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5025 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5026 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5027 }
5028
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005029 // in-call: always cap earpiece volume by voice volume + some low headroom
5030 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5031 switch (stream) {
5032 case AUDIO_STREAM_SYSTEM:
5033 case AUDIO_STREAM_RING:
5034 case AUDIO_STREAM_MUSIC:
5035 case AUDIO_STREAM_ALARM:
5036 case AUDIO_STREAM_NOTIFICATION:
5037 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5038 case AUDIO_STREAM_DTMF:
5039 case AUDIO_STREAM_ACCESSIBILITY: {
5040 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5041 + IN_CALL_EARPIECE_HEADROOM_DB;
5042 if (volumeDB > maxVoiceVolDb) {
5043 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5044 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5045 volumeDB = maxVoiceVolDb;
5046 }
5047 } break;
5048 default:
5049 break;
5050 }
5051 }
5052
Eric Laurente552edb2014-03-10 17:42:56 -07005053 // if a headset is connected, apply the following rules to ring tones and notifications
5054 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005055 // - always attenuate notifications volume by 6dB
5056 // - attenuate ring tones volume by 6dB unless music is not playing and
5057 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005058 // - if music is playing, always limit the volume to current music volume,
5059 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005060 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005061 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5062 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5063 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005064 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5065 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005066 ((stream_strategy == STRATEGY_SONIFICATION)
5067 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005068 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005069 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005070 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005071 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005072 // when the phone is ringing we must consider that music could have been paused just before
5073 // by the music application and behave as if music was active if the last music track was
5074 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005075 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005076 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005077 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005078 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005079 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005080 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5081 musicDevice),
5082 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005083 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5084 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005085 if (volumeDB > minVolDB) {
5086 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005087 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005088 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005089 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5090 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5091 // on A2DP, also ensure notification volume is not too low compared to media when
5092 // intended to be played
5093 if ((volumeDB > -96.0f) &&
5094 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5095 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5096 stream, device,
5097 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5098 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5099 }
5100 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005101 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5102 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005103 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005104 }
5105 }
5106
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005107 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005108}
5109
Eric Laurente0720872014-03-11 09:30:41 -07005110status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005111 int index,
5112 const sp<AudioOutputDescriptor>& outputDesc,
5113 audio_devices_t device,
5114 int delayMs,
5115 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005116{
Eric Laurente552edb2014-03-10 17:42:56 -07005117 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005118 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005119 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005120 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005121 return NO_ERROR;
5122 }
François Gaffie2110e042015-03-24 08:41:51 +01005123 audio_policy_forced_cfg_t forceUseForComm =
5124 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005125 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005126 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5127 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005128 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005129 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 return INVALID_OPERATION;
5131 }
5132
Eric Laurentc75307b2015-03-17 15:29:32 -07005133 if (device == AUDIO_DEVICE_NONE) {
5134 device = outputDesc->device();
5135 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005136
Eric Laurentffbc80f2015-03-18 18:30:19 -07005137 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005138 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005139 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005140 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005141
Eric Laurentffbc80f2015-03-18 18:30:19 -07005142 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005143
Eric Laurent3b73df72014-03-11 09:06:29 -07005144 if (stream == AUDIO_STREAM_VOICE_CALL ||
5145 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005146 float voiceVolume;
5147 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005148 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005149 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 } else {
5151 voiceVolume = 1.0;
5152 }
5153
Eric Laurent18fba842016-03-31 14:41:26 -07005154 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005155 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5156 mLastVoiceVolume = voiceVolume;
5157 }
5158 }
5159
5160 return NO_ERROR;
5161}
5162
Eric Laurentc75307b2015-03-17 15:29:32 -07005163void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5164 audio_devices_t device,
5165 int delayMs,
5166 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005167{
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005169
Eric Laurent794fde22016-03-11 09:50:45 -08005170 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005171 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005172 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005173 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005174 device,
5175 delayMs,
5176 force);
5177 }
5178}
5179
Eric Laurente0720872014-03-11 09:30:41 -07005180void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 bool on,
5182 const sp<AudioOutputDescriptor>& outputDesc,
5183 int delayMs,
5184 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005185{
Eric Laurent72249d52015-06-08 11:12:15 -07005186 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5187 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005188 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005189 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005191 }
5192 }
5193}
5194
Eric Laurente0720872014-03-11 09:30:41 -07005195void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005196 bool on,
5197 const sp<AudioOutputDescriptor>& outputDesc,
5198 int delayMs,
5199 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005200{
Eric Laurente552edb2014-03-10 17:42:56 -07005201 if (device == AUDIO_DEVICE_NONE) {
5202 device = outputDesc->device();
5203 }
5204
Eric Laurentc75307b2015-03-17 15:29:32 -07005205 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5206 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005207
5208 if (on) {
5209 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005210 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005211 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005212 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005213 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005214 }
5215 }
5216 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5217 outputDesc->mMuteCount[stream]++;
5218 } else {
5219 if (outputDesc->mMuteCount[stream] == 0) {
5220 ALOGV("setStreamMute() unmuting non muted stream!");
5221 return;
5222 }
5223 if (--outputDesc->mMuteCount[stream] == 0) {
5224 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005225 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005226 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005227 device,
5228 delayMs);
5229 }
5230 }
5231}
5232
Eric Laurente0720872014-03-11 09:30:41 -07005233void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005234 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005235{
Eric Laurent87ffa392015-05-22 10:32:38 -07005236 if(!hasPrimaryOutput()) {
5237 return;
5238 }
5239
Eric Laurente552edb2014-03-10 17:42:56 -07005240 // if the stream pertains to sonification strategy and we are in call we must
5241 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5242 // in the device used for phone strategy and play the tone if the selected device does not
5243 // interfere with the device used for phone strategy
5244 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5245 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005246 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005247 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5248 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005249 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005250 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5251 stream, starting, outputDesc->mDevice, stateChange);
5252 if (outputDesc->mRefCount[stream]) {
5253 int muteCount = 1;
5254 if (stateChange) {
5255 muteCount = outputDesc->mRefCount[stream];
5256 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005257 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5259 for (int i = 0; i < muteCount; i++) {
5260 setStreamMute(stream, starting, mPrimaryOutput);
5261 }
5262 } else {
5263 ALOGV("handleIncallSonification() high visibility");
5264 if (outputDesc->device() &
5265 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5266 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5267 for (int i = 0; i < muteCount; i++) {
5268 setStreamMute(stream, starting, mPrimaryOutput);
5269 }
5270 }
5271 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005272 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5273 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005274 } else {
5275 mpClientInterface->stopTone();
5276 }
5277 }
5278 }
5279 }
5280}
5281
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005282audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5283{
5284 // flags to stream type mapping
5285 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5286 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5287 }
5288 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5289 return AUDIO_STREAM_BLUETOOTH_SCO;
5290 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005291 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5292 return AUDIO_STREAM_TTS;
5293 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005294
5295 // usage to stream type mapping
5296 switch (attr->usage) {
5297 case AUDIO_USAGE_MEDIA:
5298 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005299 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005300 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5301 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005302 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5303 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005304 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5305 return AUDIO_STREAM_SYSTEM;
5306 case AUDIO_USAGE_VOICE_COMMUNICATION:
5307 return AUDIO_STREAM_VOICE_CALL;
5308
5309 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5310 return AUDIO_STREAM_DTMF;
5311
5312 case AUDIO_USAGE_ALARM:
5313 return AUDIO_STREAM_ALARM;
5314 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5315 return AUDIO_STREAM_RING;
5316
5317 case AUDIO_USAGE_NOTIFICATION:
5318 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5319 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5320 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5321 case AUDIO_USAGE_NOTIFICATION_EVENT:
5322 return AUDIO_STREAM_NOTIFICATION;
5323
5324 case AUDIO_USAGE_UNKNOWN:
5325 default:
5326 return AUDIO_STREAM_MUSIC;
5327 }
5328}
Eric Laurente83b55d2014-11-14 10:06:21 -08005329
François Gaffie53615e22015-03-19 09:24:12 +01005330bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5331{
Eric Laurente83b55d2014-11-14 10:06:21 -08005332 // has flags that map to a strategy?
5333 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5334 return true;
5335 }
5336
5337 // has known usage?
5338 switch (paa->usage) {
5339 case AUDIO_USAGE_UNKNOWN:
5340 case AUDIO_USAGE_MEDIA:
5341 case AUDIO_USAGE_VOICE_COMMUNICATION:
5342 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5343 case AUDIO_USAGE_ALARM:
5344 case AUDIO_USAGE_NOTIFICATION:
5345 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5346 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5347 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5348 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5349 case AUDIO_USAGE_NOTIFICATION_EVENT:
5350 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5351 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5352 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5353 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005354 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005355 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005356 break;
5357 default:
5358 return false;
5359 }
5360 return true;
5361}
5362
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005363bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005364 routing_strategy strategy, uint32_t inPastMs,
5365 nsecs_t sysTime) const
5366{
5367 if ((sysTime == 0) && (inPastMs != 0)) {
5368 sysTime = systemTime();
5369 }
Eric Laurent794fde22016-03-11 09:50:45 -08005370 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005371 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5372 (NUM_STRATEGIES == strategy)) &&
5373 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5374 return true;
5375 }
5376 }
5377 return false;
5378}
5379
François Gaffie2110e042015-03-24 08:41:51 +01005380audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5381{
5382 return mEngine->getForceUse(usage);
5383}
5384
5385bool AudioPolicyManager::isInCall()
5386{
5387 return isStateInCall(mEngine->getPhoneState());
5388}
5389
5390bool AudioPolicyManager::isStateInCall(int state)
5391{
5392 return is_state_in_call(state);
5393}
5394
Eric Laurentd60560a2015-04-10 11:31:20 -07005395void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5396{
5397 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5398 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5399 if (sourceDesc->mDevice->equals(deviceDesc)) {
5400 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5401 stopAudioSource(sourceDesc->getHandle());
5402 }
5403 }
5404
5405 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5406 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5407 bool release = false;
5408 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5409 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5410 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5411 source->ext.device.type == deviceDesc->type()) {
5412 release = true;
5413 }
5414 }
5415 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5416 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5417 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5418 sink->ext.device.type == deviceDesc->type()) {
5419 release = true;
5420 }
5421 }
5422 if (release) {
5423 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5424 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5425 }
5426 }
5427}
5428
Phil Burk09bc4612016-02-24 15:58:15 -08005429// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005430void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5431 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005432 // TODO Set this based on Config properties.
5433 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005434
5435 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5436 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005437 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005438
5439 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005440 bool supportsAC3 = false;
5441 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005442 bool supportsIEC61937 = false;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005443 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
Phil Burk09bc4612016-02-24 15:58:15 -08005444 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005445 switch (format) {
5446 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005447 supportsAC3 = true;
5448 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005449 case AUDIO_FORMAT_E_AC3:
5450 case AUDIO_FORMAT_DTS:
5451 case AUDIO_FORMAT_DTS_HD:
jiabindd601152017-11-27 14:53:37 -08005452 // If ALWAYS, remove all other surround formats here since we will add them later.
5453 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5454 formats.removeAt(formatIndex);
5455 formatIndex--;
5456 }
Phil Burk07ac1142016-03-25 13:39:29 -07005457 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005458 break;
5459 case AUDIO_FORMAT_IEC61937:
5460 supportsIEC61937 = true;
5461 break;
5462 default:
5463 break;
5464 }
5465 }
Phil Burk09bc4612016-02-24 15:58:15 -08005466
5467 // Modify formats based on surround preferences.
5468 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005469 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5470 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5471 // Remove surround sound related formats.
5472 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5473 audio_format_t format = formats[formatIndex];
5474 switch(format) {
5475 case AUDIO_FORMAT_AC3:
5476 case AUDIO_FORMAT_E_AC3:
5477 case AUDIO_FORMAT_DTS:
5478 case AUDIO_FORMAT_DTS_HD:
5479 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005480 formats.removeAt(formatIndex);
5481 break;
5482 default:
5483 formatIndex++; // keep it
5484 break;
5485 }
Phil Burk09bc4612016-02-24 15:58:15 -08005486 }
Phil Burk07ac1142016-03-25 13:39:29 -07005487 supportsAC3 = false;
5488 supportsOtherSurround = false;
5489 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005490 }
Phil Burk07ac1142016-03-25 13:39:29 -07005491 } else { // AUTO or ALWAYS
5492 // Most TVs support AC3 even if they do not report it in the EDID.
5493 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5494 && !supportsAC3) {
5495 formats.add(AUDIO_FORMAT_AC3);
5496 supportsAC3 = true;
5497 }
5498
5499 // If ALWAYS, add support for raw surround formats if all are missing.
5500 // This assumes that if any of these formats are reported by the HAL
5501 // then the report is valid and should not be modified.
jiabindd601152017-11-27 14:53:37 -08005502 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
Phil Burk07ac1142016-03-25 13:39:29 -07005503 formats.add(AUDIO_FORMAT_E_AC3);
5504 formats.add(AUDIO_FORMAT_DTS);
5505 formats.add(AUDIO_FORMAT_DTS_HD);
5506 supportsOtherSurround = true;
5507 }
5508
5509 // Add support for IEC61937 if any raw surround supported.
5510 // The HAL could do this but add it here, just in case.
5511 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5512 formats.add(AUDIO_FORMAT_IEC61937);
5513 supportsIEC61937 = true;
5514 }
Phil Burk09bc4612016-02-24 15:58:15 -08005515 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005516}
5517
5518// Modify the list of channel masks supported.
5519void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5520 ChannelsVector &channelMasks = *channelMasksPtr;
5521 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5522 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5523
5524 // If NEVER, then remove support for channelMasks > stereo.
5525 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5526 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5527 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5528 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5529 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5530 channelMasks.removeAt(maskIndex);
5531 } else {
5532 maskIndex++;
5533 }
5534 }
5535 // If ALWAYS, then make sure we at least support 5.1
5536 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5537 bool supports5dot1 = false;
5538 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005539 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005540 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5541 supports5dot1 = true;
5542 break;
5543 }
5544 }
5545 // If not then add 5.1 support.
5546 if (!supports5dot1) {
5547 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5548 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5549 }
Phil Burk09bc4612016-02-24 15:58:15 -08005550 }
5551}
5552
Phil Burk00eeb322016-03-31 12:41:00 -07005553void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5554 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005555 AudioProfileVector &profiles)
5556{
5557 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005558
François Gaffie112b0af2015-11-19 16:13:25 +01005559 // Format MUST be checked first to update the list of AudioProfile
5560 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005561 reply = mpClientInterface->getParameters(
5562 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005563 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005564 AudioParameter repliedParameters(reply);
5565 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005566 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005567 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5568 return;
5569 }
Phil Burk09bc4612016-02-24 15:58:15 -08005570 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005571 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005572 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005573 }
Phil Burk09bc4612016-02-24 15:58:15 -08005574 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005575 }
François Gaffie112b0af2015-11-19 16:13:25 +01005576
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005577 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005578 ChannelsVector channelMasks;
5579 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005580 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005581 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005582
5583 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005584 reply = mpClientInterface->getParameters(
5585 ioHandle,
5586 requestedParameters.toString() + ";" +
5587 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005588 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005589 AudioParameter repliedParameters(reply);
5590 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005591 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005592 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005593 }
5594 }
5595 if (profiles.hasDynamicChannelsFor(format)) {
5596 reply = mpClientInterface->getParameters(ioHandle,
5597 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005598 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005599 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005600 AudioParameter repliedParameters(reply);
5601 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005602 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005603 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005604 if (device == AUDIO_DEVICE_OUT_HDMI) {
5605 filterSurroundChannelMasks(&channelMasks);
5606 }
François Gaffie112b0af2015-11-19 16:13:25 +01005607 }
5608 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005609 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005610 }
5611}
Eric Laurentd60560a2015-04-10 11:31:20 -07005612
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005613} // namespace android