blob: f680866823b8006bb1236dafe226f03c61bf5007 [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 Laurentc2730ba2014-07-20 15:47:07 -0700389 status_t status;
390 audio_patch_handle_t afPatchHandle;
391 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700392 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700393
Andy Hunga76c7de2016-12-13 19:14:31 -0800394 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700395 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700396 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800397 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700398 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
399
400 // release existing RX patch if any
401 if (mCallRxPatch != 0) {
402 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
403 mCallRxPatch.clear();
404 }
405 // release TX patch if any
406 if (mCallTxPatch != 0) {
407 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
408 mCallTxPatch.clear();
409 }
410
411 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
412 // via setOutputDevice() on primary output.
413 // Otherwise, create two audio patches for TX and RX path.
414 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700415 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 // If the TX device is also on the primary HW module, setOutputDevice() will take care
417 // of it due to legacy implementation. If not, create a patch.
418 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
419 == AUDIO_DEVICE_NONE) {
420 createTxPatch = true;
421 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700422 } else { // create RX path audio patch
423 struct audio_patch patch;
424
425 patch.num_sources = 1;
426 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
428 ALOG_ASSERT(!deviceList.isEmpty(),
429 "updateCallRouting() selected device not in output device list");
430 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
431 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
432 ALOG_ASSERT(!deviceList.isEmpty(),
433 "updateCallRouting() no telephony RX device");
434 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
435
436 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
437 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
438
439 // request to reuse existing output stream if one is already opened to reach the RX device
440 SortedVector<audio_io_handle_t> outputs =
441 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700442 audio_io_handle_t output = selectOutput(outputs,
443 AUDIO_OUTPUT_FLAG_NONE,
444 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700446 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700447 ALOG_ASSERT(!outputDesc->isDuplicated(),
448 "updateCallRouting() RX device output is duplicated");
449 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700450 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451 patch.num_sources = 2;
452 }
453
454 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700455 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700456 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
457 status);
458 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100459 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 mCallRxPatch->mAfPatchHandle = afPatchHandle;
461 mCallRxPatch->mUid = mUidCached;
462 }
463 createTxPatch = true;
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700466 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700467
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 patch.num_sources = 1;
469 patch.num_sinks = 1;
470 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
471 ALOG_ASSERT(!deviceList.isEmpty(),
472 "updateCallRouting() selected device not in input device list");
473 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
474 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
475 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
476 ALOG_ASSERT(!deviceList.isEmpty(),
477 "updateCallRouting() no telephony TX device");
478 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
479 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
480
481 SortedVector<audio_io_handle_t> outputs =
482 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700483 audio_io_handle_t output = selectOutput(outputs,
484 AUDIO_OUTPUT_FLAG_NONE,
485 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700486 // request to reuse existing output stream if one is already opened to reach the TX
487 // path output device
488 if (output != AUDIO_IO_HANDLE_NONE) {
489 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
490 ALOG_ASSERT(!outputDesc->isDuplicated(),
491 "updateCallRouting() RX device output is duplicated");
492 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700493 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700494 patch.num_sources = 2;
495 }
496
Eric Laurentc0a889f2015-10-14 14:36:34 -0700497 // terminate active capture if on the same HW module as the call TX source device
498 // FIXME: would be better to refine to only inputs whose profile connects to the
499 // call TX device but this information is not in the audio patch and logic here must be
500 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
503 AudioSessionCollection activeSessions =
504 activeDesc->getAudioSessions(true /*activeOnly*/);
505 for (size_t j = 0; j < activeSessions.size(); j++) {
506 audio_session_t activeSession = activeSessions.keyAt(j);
507 stopInput(activeDesc->mIoHandle, activeSession);
508 releaseInput(activeDesc->mIoHandle, activeSession);
509 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700510 }
511 }
512
Eric Laurentc2730ba2014-07-20 15:47:07 -0700513 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700514 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700515 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
516 status);
517 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100518 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519 mCallTxPatch->mAfPatchHandle = afPatchHandle;
520 mCallTxPatch->mUid = mUidCached;
521 }
522 }
Eric Laurentdc462862016-07-19 12:29:53 -0700523
524 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700525}
526
Eric Laurente0720872014-03-11 09:30:41 -0700527void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700528{
529 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100530 // store previous phone state for management of sonification strategy below
531 int oldState = mEngine->getPhoneState();
532
533 if (mEngine->setPhoneState(state) != NO_ERROR) {
534 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700535 return;
536 }
François Gaffie2110e042015-03-24 08:41:51 +0100537 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700538 // if leaving call state, handle special case of active streams
539 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700541 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800542 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700543 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800545
Eric Laurent63dea1d2015-07-02 17:10:28 -0700546 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800547 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700548 }
549
François Gaffie2110e042015-03-24 08:41:51 +0100550 /**
551 * Switching to or from incall state or switching between telephony and VoIP lead to force
552 * routing command.
553 */
554 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
555 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700556
557 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700558 checkA2dpSuspend();
559 checkOutputForAllStrategies();
560 updateDevicesAndOutputs();
561
Eric Laurente552edb2014-03-10 17:42:56 -0700562 int delayMs = 0;
563 if (isStateInCall(state)) {
564 nsecs_t sysTime = systemTime();
565 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700566 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700567 // mute media and sonification strategies and delay device switch by the largest
568 // latency of any output where either strategy is active.
569 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100570 if ((isStrategyActive(desc, STRATEGY_MEDIA,
571 SONIFICATION_HEADSET_MUSIC_DELAY,
572 sysTime) ||
573 isStrategyActive(desc, STRATEGY_SONIFICATION,
574 SONIFICATION_HEADSET_MUSIC_DELAY,
575 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 (delayMs < (int)desc->latency()*2)) {
577 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700578 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 setStrategyMute(STRATEGY_MEDIA, true, desc);
580 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700581 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
583 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700584 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
585 }
586 }
587
Eric Laurent87ffa392015-05-22 10:32:38 -0700588 if (hasPrimaryOutput()) {
589 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
590 // the device returned is not necessarily reachable via this output
591 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
592 // force routing command to audio hardware when ending call
593 // even if no device change is needed
594 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
595 rxDevice = mPrimaryOutput->device();
596 }
Eric Laurente552edb2014-03-10 17:42:56 -0700597
Eric Laurent87ffa392015-05-22 10:32:38 -0700598 if (state == AUDIO_MODE_IN_CALL) {
599 updateCallRouting(rxDevice, delayMs);
600 } else if (oldState == AUDIO_MODE_IN_CALL) {
601 if (mCallRxPatch != 0) {
602 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
603 mCallRxPatch.clear();
604 }
605 if (mCallTxPatch != 0) {
606 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
607 mCallTxPatch.clear();
608 }
609 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
610 } else {
611 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700612 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700613 }
Eric Laurente552edb2014-03-10 17:42:56 -0700614 // if entering in call state, handle special case of active streams
615 // pertaining to sonification strategy see handleIncallSonification()
616 if (isStateInCall(state)) {
617 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800618 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700619 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700621
622 // force reevaluating accessibility routing when call starts
623 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700624 }
625
626 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700627 if (state == AUDIO_MODE_RINGTONE &&
628 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700629 mLimitRingtoneVolume = true;
630 } else {
631 mLimitRingtoneVolume = false;
632 }
633}
634
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700635audio_mode_t AudioPolicyManager::getPhoneState() {
636 return mEngine->getPhoneState();
637}
638
Eric Laurente0720872014-03-11 09:30:41 -0700639void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700640 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700641{
François Gaffie2110e042015-03-24 08:41:51 +0100642 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700643 if (config == mEngine->getForceUse(usage)) {
644 return;
645 }
Eric Laurente552edb2014-03-10 17:42:56 -0700646
François Gaffie2110e042015-03-24 08:41:51 +0100647 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
648 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
649 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700650 }
François Gaffie2110e042015-03-24 08:41:51 +0100651 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
652 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
653 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700654
655 // check for device and output changes triggered by new force usage
656 checkA2dpSuspend();
657 checkOutputForAllStrategies();
658 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800659
Eric Laurentdc462862016-07-19 12:29:53 -0700660 //FIXME: workaround for truncated touch sounds
661 // to be removed when the problem is handled by system UI
662 uint32_t delayMs = 0;
663 uint32_t waitMs = 0;
664 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
665 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
666 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700667 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700669 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
673 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
674 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700675 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
676 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677 }
Eric Laurente552edb2014-03-10 17:42:56 -0700678 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700679 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700680 }
681 }
682
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800683 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800684 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 if (activeDesc->mProfile->getSupportedDevices().types() &
687 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
688 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700689 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800690 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693}
694
Eric Laurente0720872014-03-11 09:30:41 -0700695void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700696{
697 ALOGV("setSystemProperty() property %s, value %s", property, value);
698}
699
700// Find a direct output profile compatible with the parameters passed, even if the input flags do
701// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800702sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700703 audio_devices_t device,
704 uint32_t samplingRate,
705 audio_format_t format,
706 audio_channel_mask_t channelMask,
707 audio_output_flags_t flags)
708{
Eric Laurent861a6282015-05-18 15:40:16 -0700709 // only retain flags that will drive the direct output profile selection
710 // if explicitly requested
711 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700712 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
713 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700714 flags =
715 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
716
717 sp<IOProfile> profile;
718
Mikhail Naganovd4120142017-12-06 15:49:22 -0800719 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800720 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700721 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700722 samplingRate, NULL /*updatedSamplingRate*/,
723 format, NULL /*updatedFormat*/,
724 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700725 flags)) {
726 continue;
727 }
728 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100729 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 continue;
731 }
732 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100733 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700734 continue;
735 }
736 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700739 }
Eric Laurente552edb2014-03-10 17:42:56 -0700740 }
741 }
Eric Laurent861a6282015-05-18 15:40:16 -0700742 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700743}
744
Eric Laurentf4e63452017-11-06 19:31:46 +0000745audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700746{
Eric Laurent3b73df72014-03-11 09:06:29 -0700747 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700748 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800749
750 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
751 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
752 // format, flags, etc. This may result in some discrepancy for functions that utilize
753 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
754 // and AudioSystem::getOutputSamplingRate().
755
Eric Laurentf4e63452017-11-06 19:31:46 +0000756 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
757 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700758
Eric Laurentf4e63452017-11-06 19:31:46 +0000759 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
760 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700761}
762
Eric Laurente83b55d2014-11-14 10:06:21 -0800763status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
764 audio_io_handle_t *output,
765 audio_session_t session,
766 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700767 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800768 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800769 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700770 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800771 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700772{
Eric Laurente83b55d2014-11-14 10:06:21 -0800773 audio_attributes_t attributes;
774 if (attr != NULL) {
775 if (!isValidAttributes(attr)) {
776 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
777 attr->usage, attr->content_type, attr->flags,
778 attr->tags);
779 return BAD_VALUE;
780 }
781 attributes = *attr;
782 } else {
783 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
784 ALOGE("getOutputForAttr(): invalid stream type");
785 return BAD_VALUE;
786 }
787 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700788 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800789
790 // TODO: check for existing client for this port ID
791 if (*portId == AUDIO_PORT_HANDLE_NONE) {
792 *portId = AudioPort::getNextUniqueId();
793 }
794
Eric Laurentc75307b2015-03-17 15:29:32 -0700795 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800796 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100797 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800798 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100799 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800800 }
François Gaffie036e1e92015-03-19 10:16:24 +0100801 *stream = streamTypefromAttributesInt(&attributes);
802 *output = desc->mIoHandle;
803 ALOGV("getOutputForAttr() returns output %d", *output);
804 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800805 }
806 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
807 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
808 return BAD_VALUE;
809 }
810
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700811 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
812 " session %d selectedDeviceId %d",
813 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700814 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700815
816 *stream = streamTypefromAttributesInt(&attributes);
817
818 // Explicit routing?
819 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700820 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800821 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700822 }
823 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700824
Eric Laurente83b55d2014-11-14 10:06:21 -0800825 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700827
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700829 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
830 }
831
Eric Laurentfe231122017-11-17 17:48:06 -0800832 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %x, channel mask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800833 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834
Eric Laurentfe231122017-11-17 17:48:06 -0800835 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700837 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800838 return INVALID_OPERATION;
839 }
Paul McLeanaa981192015-03-21 09:55:15 -0700840
Eric Laurent2ac76942017-06-22 17:17:09 -0700841 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
842 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
843 : AUDIO_PORT_HANDLE_NONE;
844
845 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
846
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848}
849
850audio_io_handle_t AudioPolicyManager::getOutputForDevice(
851 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800852 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700853 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800854 const audio_config_t *config,
855 audio_output_flags_t flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700856{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700857 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700858 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859
Eric Laurente552edb2014-03-10 17:42:56 -0700860 // open a direct output if required by specified parameters
861 //force direct flag if offload flag is set: offloading implies a direct output stream
862 // and all common behaviors are driven by checking only the direct flag
863 // this should normally be set appropriately in the policy configuration file
864 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700865 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700867 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
868 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
869 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800870 // only allow deep buffering for music stream type
871 if (stream != AUDIO_STREAM_MUSIC) {
872 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700873 } else if (/* stream == AUDIO_STREAM_MUSIC && */
874 flags == AUDIO_OUTPUT_FLAG_NONE &&
875 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
876 // use DEEP_BUFFER as default output for music stream type
877 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800878 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700879 if (stream == AUDIO_STREAM_TTS) {
880 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700881 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800882 audio_is_linear_pcm(config->format)) {
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700883 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
884 AUDIO_OUTPUT_FLAG_DIRECT);
885 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700886 }
Eric Laurente552edb2014-03-10 17:42:56 -0700887
Eric Laurentb732cf52014-09-24 19:08:21 -0700888 sp<IOProfile> profile;
889
890 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700891 // and not explicitly requested
892 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800893 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
894 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700895 goto non_direct_output;
896 }
897
Andy Hung2ddee192015-12-18 17:34:44 -0800898 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
899 // This prevents creating an offloaded track and tearing it down immediately after start
900 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700901 // FIXME: We should check the audio session here but we do not have it in this context.
902 // This may prevent offloading in rare situations where effects are left active by apps
903 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700904
Eric Laurente552edb2014-03-10 17:42:56 -0700905 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800906 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700907 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800908 config->sample_rate,
909 config->format,
910 config->channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -0700911 (audio_output_flags_t)flags);
912 }
913
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 if (profile != 0) {
Eric Laurent7b0e9532017-12-07 12:20:56 -0800915 sp<SwAudioOutputDescriptor> outputDesc = NULL;
916
Eric Laurente552edb2014-03-10 17:42:56 -0700917 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
Eric Laurent7b0e9532017-12-07 12:20:56 -0800920 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800921 // reuse direct output if currently open by the same client
922 // and configured with same parameters
Eric Laurent7b0e9532017-12-07 12:20:56 -0800923 if ((config->sample_rate == outputDesc->mSamplingRate) &&
924 audio_formats_match(config->format, outputDesc->mFormat) &&
925 (config->channel_mask == outputDesc->mChannelMask)) {
926 if (session == outputDesc->mDirectClientSession) {
927 outputDesc->mDirectOpenCount++;
928 ALOGV("getOutputForDevice() reusing direct output %d for session %d",
929 mOutputs.keyAt(i), session);
930 return mOutputs.keyAt(i);
931 } else {
932 ALOGV("getOutputForDevice() do not reuse direct output because"
933 "current client (%d) is not the same as requesting client (%d)",
934 outputDesc->mDirectClientSession, session);
935 goto non_direct_output;
936 }
Eric Laurente552edb2014-03-10 17:42:56 -0700937 }
938 }
939 }
Eric Laurent7b0e9532017-12-07 12:20:56 -0800940 // close direct output if currently open and configured with different parameters
941 if (outputDesc != NULL) {
942 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
Eric Laurent861a6282015-05-18 15:40:16 -0700944
Eric Laurent7b0e9532017-12-07 12:20:56 -0800945 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentfe231122017-11-17 17:48:06 -0800946 status = outputDesc->open(config, device, String8(""), stream, flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700947
948 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700949 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800950 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
951 (config->format != AUDIO_FORMAT_DEFAULT &&
952 !audio_formats_match(config->format, outputDesc->mFormat)) ||
953 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
954 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
955 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
956 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
957 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700958 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800959 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700960 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800961 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800962 if (audio_is_linear_pcm(config->format) &&
963 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800964 goto non_direct_output;
965 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700966 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700968 outputDesc->mRefCount[stream] = 0;
969 outputDesc->mStopTime[stream] = 0;
970 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800971 outputDesc->mDirectClientSession = session;
972
Eric Laurente552edb2014-03-10 17:42:56 -0700973 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700974 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000975 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700976 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700977 return output;
978 }
979
Eric Laurentb732cf52014-09-24 19:08:21 -0700980non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700981
982 // A request for HW A/V sync cannot fallback to a mixed output because time
983 // stamps are embedded in audio data
984 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
985 return AUDIO_IO_HANDLE_NONE;
986 }
987
Eric Laurente552edb2014-03-10 17:42:56 -0700988 // ignoring channel mask due to downmix capability in mixer
989
990 // open a non direct output
991
992 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -0800993 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700994 // get which output is suitable for the specified stream. The actual
995 // routing change will happen when startOutput() will be called
996 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
997
Eric Laurent8838a382014-09-08 16:44:28 -0700998 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
999 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurentfe231122017-11-17 17:48:06 -08001000 output = selectOutput(outputs, flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001001 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001002 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Eric Laurentfe231122017-11-17 17:48:06 -08001003 "sampling rate %d, format %d, channels %x, flags %x",
1004 stream, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001005
Eric Laurente552edb2014-03-10 17:42:56 -07001006 return output;
1007}
1008
Eric Laurente0720872014-03-11 09:30:41 -07001009audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001010 audio_output_flags_t flags,
1011 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001012{
1013 // select one output among several that provide a path to a particular device or set of
1014 // devices (the list was previously build by getOutputsForDevice()).
1015 // The priority is as follows:
1016 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001017 // 2: the output with the bit depth the closest to the requested one
1018 // 3: the primary output
1019 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001020
1021 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001022 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001023 }
1024 if (outputs.size() == 1) {
1025 return outputs[0];
1026 }
1027
1028 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001029 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1030 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1031 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001032 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1033 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001034
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001035 for (audio_io_handle_t output : outputs) {
1036 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001037 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001038 // if a valid format is specified, skip output if not compatible
1039 if (format != AUDIO_FORMAT_INVALID) {
1040 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001041 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001042 continue;
1043 }
1044 } else if (!audio_is_linear_pcm(format)) {
1045 continue;
1046 }
Eric Laurente6930022016-02-11 10:20:40 -08001047 if (AudioPort::isBetterFormatMatch(
1048 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001049 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001050 bestFormat = outputDesc->mFormat;
1051 }
Eric Laurent8838a382014-09-08 16:44:28 -07001052 }
1053
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001054 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001055 if (commonFlags >= maxCommonFlags) {
1056 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001057 if (format != AUDIO_FORMAT_INVALID
1058 && AudioPort::isBetterFormatMatch(
1059 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001060 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001061 bestFormatForFlags = outputDesc->mFormat;
1062 }
1063 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001064 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001065 maxCommonFlags = commonFlags;
1066 bestFormatForFlags = outputDesc->mFormat;
1067 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001068 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001070 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001071 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001072 }
1073 }
1074 }
1075
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001076 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001077 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001078 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001079 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001080 return outputForFormat;
1081 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001082 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001083 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
1085
1086 return outputs[0];
1087}
1088
Eric Laurente0720872014-03-11 09:30:41 -07001089status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001090 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001091 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001092{
Paul McLeanaa981192015-03-21 09:55:15 -07001093 ALOGV("startOutput() output %d, stream %d, session %d",
1094 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 ssize_t index = mOutputs.indexOfKey(output);
1096 if (index < 0) {
1097 ALOGW("startOutput() unknown output %d", output);
1098 return BAD_VALUE;
1099 }
1100
Eric Laurentc75307b2015-03-17 15:29:32 -07001101 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1102
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001103 // Routing?
1104 mOutputRoutes.incRouteActivity(session);
1105
Eric Laurentc75307b2015-03-17 15:29:32 -07001106 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001107 AudioMix *policyMix = NULL;
1108 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001109 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001110 policyMix = outputDesc->mPolicyMix;
1111 address = policyMix->mDeviceAddress.string();
1112 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1113 newDevice = policyMix->mDeviceType;
1114 } else {
1115 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1116 }
Eric Laurent493404d2015-04-21 15:07:36 -07001117 } else if (mOutputRoutes.hasRouteChanged(session)) {
1118 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001119 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001120 } else {
1121 newDevice = AUDIO_DEVICE_NONE;
1122 }
1123
1124 uint32_t delayMs = 0;
1125
Eric Laurentc40d9692016-04-13 19:14:13 -07001126 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001127
1128 if (status != NO_ERROR) {
1129 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001130 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001131 }
1132 // Automatically enable the remote submix input when output is started on a re routing mix
1133 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001134 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1135 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001136 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1137 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001138 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001139 "remote-submix");
1140 }
1141
1142 if (delayMs != 0) {
1143 usleep(delayMs * 1000);
1144 }
1145
1146 return status;
1147}
1148
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001149status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001150 audio_stream_type_t stream,
1151 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001152 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 uint32_t *delayMs)
1154{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001155 // cannot start playback of STREAM_TTS if any other output is being used
1156 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001157
1158 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001159 if (stream == AUDIO_STREAM_TTS) {
1160 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001161 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001162 return INVALID_OPERATION;
1163 } else {
1164 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1165 }
1166 } else {
1167 // some playback other than beacon starts
1168 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1169 }
1170
Eric Laurent77305a62016-07-25 16:39:22 -07001171 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001172 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001173 bool force = !outputDesc->isActive() &&
1174 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001175
Andy Hung7c7124e2017-10-20 12:03:34 -07001176 // requiresMuteCheck is false when we can bypass mute strategy.
1177 // It covers a common case when there is no materially active audio
1178 // and muting would result in unnecessary delay and dropped audio.
1179 const uint32_t outputLatencyMs = outputDesc->latency();
1180 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1181
Eric Laurente552edb2014-03-10 17:42:56 -07001182 // increment usage count for this stream on the requested output:
1183 // NOTE that the usage count is the same for duplicated output and hardware output which is
1184 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1185 outputDesc->changeRefCount(stream, 1);
1186
Eric Laurent36829f92017-04-07 19:04:42 -07001187 if (stream == AUDIO_STREAM_MUSIC) {
1188 selectOutputForMusicEffects();
1189 }
1190
Eric Laurent493404d2015-04-21 15:07:36 -07001191 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001192 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001193 if (device == AUDIO_DEVICE_NONE) {
1194 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001195 }
Eric Laurent36829f92017-04-07 19:04:42 -07001196
Eric Laurente552edb2014-03-10 17:42:56 -07001197 routing_strategy strategy = getStrategy(stream);
1198 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001199 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1200 (beaconMuteLatency > 0);
1201 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001202 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001203 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001204 if (desc != outputDesc) {
Andy Hung7c7124e2017-10-20 12:03:34 -07001205 // An output has a shared device if
1206 // - managed by the same hw module
1207 // - supports the currently selected device
1208 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1209 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1210
Eric Laurent77305a62016-07-25 16:39:22 -07001211 // force a device change if any other output is:
1212 // - managed by the same hw module
Eric Laurent77305a62016-07-25 16:39:22 -07001213 // - supports currently selected device
Andy Hung7c7124e2017-10-20 12:03:34 -07001214 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001215 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001216 // In this case, the audio HAL must receive the new device selection so that it can
Andy Hung7c7124e2017-10-20 12:03:34 -07001217 // change the device currently selected by the other output.
1218 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001219 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001220 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001221 force = true;
1222 }
1223 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001224 // a notification so that audio focus effect can propagate, or that a mute/unmute
1225 // event occurred for beacon
Andy Hung7c7124e2017-10-20 12:03:34 -07001226 const uint32_t latencyMs = desc->latency();
1227 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1228
1229 if (shouldWait && isActive && (waitMs < latencyMs)) {
1230 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001231 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001232
1233 // Require mute check if another output is on a shared device
1234 // and currently active to have proper drain and avoid pops.
1235 // Note restoring AudioTracks onto this output needs to invoke
1236 // a volume ramp if there is no mute.
1237 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001238 }
1239 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001240
1241 const uint32_t muteWaitMs =
1242 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001243
1244 // handle special case for sonification while in call
1245 if (isInCall()) {
1246 handleIncallSonification(stream, true, false);
1247 }
1248
1249 // apply volume rules for current stream and device if necessary
1250 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001251 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001252 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001253 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001254
1255 // update the outputs if starting an output with a stream that can affect notification
1256 // routing
1257 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001258
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001259 // force reevaluating accessibility routing when ringtone or alarm starts
1260 if (strategy == STRATEGY_SONIFICATION) {
1261 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1262 }
Eric Laurentdc462862016-07-19 12:29:53 -07001263
1264 if (waitMs > muteWaitMs) {
1265 *delayMs = waitMs - muteWaitMs;
1266 }
Andy Hung7c7124e2017-10-20 12:03:34 -07001267
1268 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1269 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1270 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1271 // change occurs after the MixerThread starts and causes a stream volume
1272 // glitch.
1273 //
1274 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001275 }
Eric Laurentdc462862016-07-19 12:29:53 -07001276
Eric Laurente552edb2014-03-10 17:42:56 -07001277 return NO_ERROR;
1278}
1279
1280
Eric Laurente0720872014-03-11 09:30:41 -07001281status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001282 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001283 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001284{
1285 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1286 ssize_t index = mOutputs.indexOfKey(output);
1287 if (index < 0) {
1288 ALOGW("stopOutput() unknown output %d", output);
1289 return BAD_VALUE;
1290 }
1291
Eric Laurentc75307b2015-03-17 15:29:32 -07001292 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001293
Eric Laurentc75307b2015-03-17 15:29:32 -07001294 if (outputDesc->mRefCount[stream] == 1) {
1295 // Automatically disable the remote submix input when output is stopped on a
1296 // re routing mix of type MIX_TYPE_RECORDERS
1297 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1298 outputDesc->mPolicyMix != NULL &&
1299 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1300 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1301 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001302 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001303 "remote-submix");
1304 }
1305 }
1306
1307 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001308 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001309 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001310 int activityCount = mOutputRoutes.decRouteActivity(session);
1311 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1312
1313 if (forceDeviceUpdate) {
1314 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1315 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001316 }
1317
Eric Laurent7b0e9532017-12-07 12:20:56 -08001318 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001319}
1320
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001321status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001322 audio_stream_type_t stream,
1323 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001324{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001325 // always handle stream stop, check which stream type is stopping
1326 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1327
Eric Laurente552edb2014-03-10 17:42:56 -07001328 // handle special case for sonification while in call
1329 if (isInCall()) {
1330 handleIncallSonification(stream, false, false);
1331 }
1332
1333 if (outputDesc->mRefCount[stream] > 0) {
1334 // decrement usage count of this stream on the output
1335 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001336
Eric Laurente552edb2014-03-10 17:42:56 -07001337 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001339 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001341 // delay the device switch by twice the latency because stopOutput() is executed when
1342 // the track stop() command is received and at that time the audio track buffer can
1343 // still contain data that needs to be drained. The latency only covers the audio HAL
1344 // and kernel buffers. Also the latency does not always include additional delay in the
1345 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001347
1348 // force restoring the device selection on other active outputs if it differs from the
1349 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001350 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001351 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001352 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001353 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001354 desc->isActive() &&
1355 outputDesc->sharesHwModuleWith(desc) &&
1356 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001357 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1358 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001359 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001360 newDevice2,
1361 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001362 delayMs);
1363 // re-apply device specific volume if not done by setOutputDevice()
1364 if (!force) {
1365 applyStreamVolumes(desc, newDevice2, delayMs);
1366 }
Eric Laurente552edb2014-03-10 17:42:56 -07001367 }
1368 }
1369 // update the outputs if stopping one with a stream that can affect notification routing
1370 handleNotificationRoutingForStream(stream);
1371 }
Eric Laurent36829f92017-04-07 19:04:42 -07001372 if (stream == AUDIO_STREAM_MUSIC) {
1373 selectOutputForMusicEffects();
1374 }
Eric Laurente552edb2014-03-10 17:42:56 -07001375 return NO_ERROR;
1376 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001377 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001378 return INVALID_OPERATION;
1379 }
1380}
1381
Eric Laurente83b55d2014-11-14 10:06:21 -08001382void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001383 audio_stream_type_t stream __unused,
1384 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001385{
1386 ALOGV("releaseOutput() %d", output);
1387 ssize_t index = mOutputs.indexOfKey(output);
1388 if (index < 0) {
1389 ALOGW("releaseOutput() releasing unknown output %d", output);
1390 return;
1391 }
1392
Paul McLeanaa981192015-03-21 09:55:15 -07001393 // Routing
1394 mOutputRoutes.removeRoute(session);
1395
Eric Laurentc75307b2015-03-17 15:29:32 -07001396 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001397 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001398 if (desc->mDirectOpenCount <= 0) {
1399 ALOGW("releaseOutput() invalid open count %d for output %d",
1400 desc->mDirectOpenCount, output);
1401 return;
1402 }
1403 if (--desc->mDirectOpenCount == 0) {
1404 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001405 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001406 }
1407 }
1408}
1409
1410
Eric Laurentcaf7f482014-11-25 17:50:47 -08001411status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1412 audio_io_handle_t *input,
1413 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001414 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001415 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001416 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001417 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001418 input_type_t *inputType,
1419 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001420{
Eric Laurentfe231122017-11-17 17:48:06 -08001421 ALOGV("getInputForAttr() source %d, sampling rate %d, format %d, channel mask %x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001422 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001423 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001424
Eric Laurentad2e7b92017-09-14 20:06:42 -07001425 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001426 // handle legacy remote submix case where the address was not always specified
1427 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001428 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001429 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001430 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001431 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001432
Eric Laurentfe231122017-11-17 17:48:06 -08001433 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1434 inputSource = AUDIO_SOURCE_MIC;
1435 }
1436
Paul McLean466dc8e2015-04-17 13:15:36 -06001437 // Explicit routing?
1438 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001439 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001440 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001441 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001442 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001443
Eric Laurentad2e7b92017-09-14 20:06:42 -07001444 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1445 // possible
1446 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1447 *input != AUDIO_IO_HANDLE_NONE) {
1448 ssize_t index = mInputs.indexOfKey(*input);
1449 if (index < 0) {
1450 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1451 status = BAD_VALUE;
1452 goto error;
1453 }
1454 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1455 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1456 if (audioSession == 0) {
1457 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1458 status = BAD_VALUE;
1459 goto error;
1460 }
1461 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1462 // The second call is for the first active client and sets the UID. Any further call
1463 // corresponds to a new client and is only permitted from the same UId.
1464 if (audioSession->openCount() == 1) {
1465 audioSession->setUid(uid);
1466 } else if (audioSession->uid() != uid) {
1467 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1468 uid, session, audioSession->uid());
1469 status = INVALID_OPERATION;
1470 goto error;
1471 }
1472 audioSession->changeOpenCount(1);
1473 *inputType = API_INPUT_LEGACY;
1474 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1475 *portId = AudioPort::getNextUniqueId();
1476 }
1477 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1478 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1479 : AUDIO_PORT_HANDLE_NONE;
1480 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1481
1482 return NO_ERROR;
1483 }
1484
1485 *input = AUDIO_IO_HANDLE_NONE;
1486 *inputType = API_INPUT_INVALID;
1487
Eric Laurentad2e7b92017-09-14 20:06:42 -07001488 halInputSource = inputSource;
1489
1490 // TODO: check for existing client for this port ID
1491 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1492 *portId = AudioPort::getNextUniqueId();
1493 }
1494
1495 audio_devices_t device;
1496
Eric Laurentc447ded2015-01-06 08:47:05 -08001497 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001498 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001499 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1500 if (status != NO_ERROR) {
1501 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001502 }
1503 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001504 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1505 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001506 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001507 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001508 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001509 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001510 status = BAD_VALUE;
1511 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001512 }
Eric Laurentc722f302014-12-10 11:21:49 -08001513 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001514 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001515 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1516 // there is an external policy, but this input is attached to a mix of recorders,
1517 // meaning it receives audio injected into the framework, so the recorder doesn't
1518 // know about it and is therefore considered "legacy"
1519 *inputType = API_INPUT_LEGACY;
1520 } else {
1521 // recording a mix of players defined by an external policy, we're rerouting for
1522 // an external policy
1523 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1524 }
Eric Laurentc722f302014-12-10 11:21:49 -08001525 } else if (audio_is_remote_submix_device(device)) {
1526 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001527 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001528 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1529 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001530 } else {
1531 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001532 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001533
Eric Laurent599c7582015-12-07 18:05:55 -08001534 }
1535
1536 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001537 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001538 policyMix);
1539 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001540 status = INVALID_OPERATION;
1541 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001542 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001543
Eric Laurentad2e7b92017-09-14 20:06:42 -07001544 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001545 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1546 : AUDIO_PORT_HANDLE_NONE;
1547
1548 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1549 *input, *inputType, *selectedDeviceId);
1550
Eric Laurent599c7582015-12-07 18:05:55 -08001551 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001552
1553error:
1554 mInputRoutes.removeRoute(session);
1555 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001556}
1557
1558
1559audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1560 String8 address,
1561 audio_session_t session,
1562 uid_t uid,
1563 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001564 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001565 audio_input_flags_t flags,
1566 AudioMix *policyMix)
1567{
1568 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1569 audio_source_t halInputSource = inputSource;
1570 bool isSoundTrigger = false;
1571
1572 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1573 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1574 if (index >= 0) {
1575 input = mSoundTriggerSessions.valueFor(session);
1576 isSoundTrigger = true;
1577 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1578 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1579 } else {
1580 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001581 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001582 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001583 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001584 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001585 }
1586
Andy Hungf129b032015-04-07 13:45:50 -07001587 // find a compatible input profile (not necessarily identical in parameters)
1588 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001589 // sampling rate and flags may be updated by getInputProfile
1590 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1591 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
1592 audio_format_t profileFormat = config->format;
1593 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001594 audio_input_flags_t profileFlags = flags;
1595 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001596 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001597 profileSamplingRate, profileFormat, profileChannelMask,
1598 profileFlags);
1599 if (profile != 0) {
1600 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001601 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1602 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001603 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1604 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1605 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001606 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001607 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1608 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001609 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001610 }
Eric Laurente552edb2014-03-10 17:42:56 -07001611 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001612 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001613 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001614 if (samplingRate == 0) {
1615 samplingRate = profileSamplingRate;
1616 }
Eric Laurente552edb2014-03-10 17:42:56 -07001617
Eric Laurent322b4d22015-04-03 15:57:54 -07001618 if (profile->getModuleHandle() == 0) {
1619 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001620 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001621 }
1622
Eric Laurent599c7582015-12-07 18:05:55 -08001623 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001624 inputSource,
1625 config->format,
1626 samplingRate,
1627 config->channel_mask,
1628 flags,
1629 uid,
1630 isSoundTrigger,
1631 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001632
Eric Laurent74708e72017-04-07 17:13:42 -07001633// FIXME: disable concurrent capture until UI is ready
1634#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001635 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001636 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001637 for (size_t i = 0; i < mInputs.size(); i++) {
1638 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001639 // reuse input if:
1640 // - it shares the same profile
1641 // AND
1642 // - it is not a reroute submix input
1643 // AND
1644 // - it is: not used for sound trigger
1645 // OR
1646 // used for sound trigger and all clients use the same session ID
1647 //
1648 if ((profile == desc->mProfile) &&
1649 (isSoundTrigger == desc->isSoundTrigger()) &&
1650 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001651
1652 sp<AudioSession> as = desc->getAudioSession(session);
1653 if (as != 0) {
1654 // do not allow unmatching properties on same session
1655 if (as->matches(audioSession)) {
1656 as->changeOpenCount(1);
1657 } else {
1658 ALOGW("getInputForDevice() record with different attributes"
1659 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001660 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001661 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001662 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001663 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001664 }
Eric Laurentbb948092017-01-23 18:33:30 -08001665
Eric Laurent555530a2017-02-07 18:17:24 -08001666 // Reuse the already opened input stream on this profile if:
1667 // - the new capture source is background OR
1668 // - the path requested configurations match OR
1669 // - the new source priority is less than the highest source priority on this input
1670 // If the input stream cannot be reused, close it before opening a new stream
1671 // on the same profile for the new client so that the requested path configuration
1672 // can be selected.
1673 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001674 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001675 desc->mChannelMask != config->channel_mask ||
1676 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001677 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001678 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001679 reusedInputDesc = desc;
1680 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001681 } else {
1682 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001683 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1684 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001685 }
Eric Laurent599c7582015-12-07 18:05:55 -08001686 }
1687 }
Eric Laurent599c7582015-12-07 18:05:55 -08001688
Eric Laurent555530a2017-02-07 18:17:24 -08001689 if (reusedInputDesc != 0) {
1690 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1691 for (size_t j = 0; j < sessions.size(); j++) {
1692 audio_session_t currentSession = sessions.keyAt(j);
1693 stopInput(reusedInputDesc->mIoHandle, currentSession);
1694 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1695 }
1696 }
Eric Laurent74708e72017-04-07 17:13:42 -07001697#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001698
Eric Laurentfe231122017-11-17 17:48:06 -08001699 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001700
Eric Laurentfe231122017-11-17 17:48:06 -08001701 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1702 lConfig.sample_rate = profileSamplingRate;
1703 lConfig.channel_mask = profileChannelMask;
1704 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001705
Eric Laurentfe231122017-11-17 17:48:06 -08001706 status_t status = inputDesc->open(&lConfig, device, address,
1707 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001708
1709 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001710 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001711 (profileSamplingRate != lConfig.sample_rate) ||
1712 !audio_formats_match(profileFormat, lConfig.format) ||
1713 (profileChannelMask != lConfig.channel_mask)) {
1714 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
1715 ", format %d, channel mask %x",
1716 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001717 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001718 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001719 }
Eric Laurent599c7582015-12-07 18:05:55 -08001720 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001721 }
1722
Eric Laurentc722f302014-12-10 11:21:49 -08001723 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001724 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001725
Eric Laurent599c7582015-12-07 18:05:55 -08001726 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001727 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001728
Eric Laurent599c7582015-12-07 18:05:55 -08001729 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001730}
1731
Eric Laurentbb948092017-01-23 18:33:30 -08001732//static
1733bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1734{
1735 return (source == AUDIO_SOURCE_HOTWORD) ||
1736 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1737 (source == AUDIO_SOURCE_FM_TUNER);
1738}
1739
Eric Laurentfb66dd92016-01-28 18:32:03 -08001740bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1741 const sp<AudioSession>& audioSession)
1742{
1743 // Do not allow capture if an active voice call is using a software patch and
1744 // the call TX source device is on the same HW module.
1745 // FIXME: would be better to refine to only inputs whose profile connects to the
1746 // call TX device but this information is not in the audio patch
1747 if (mCallTxPatch != 0 &&
1748 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1749 return false;
1750 }
1751
1752 // starting concurrent capture is enabled if:
1753 // 1) capturing for re-routing
1754 // 2) capturing for HOTWORD source
1755 // 3) capturing for FM TUNER source
1756 // 3) All other active captures are either for re-routing or HOTWORD
1757
1758 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001759 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001760 return true;
1761 }
1762
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001763 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001764 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001765 !is_virtual_input_device(activeInput->mDevice)) {
1766 return false;
1767 }
1768 }
1769
1770 return true;
1771}
1772
Chris Thornton2b864642017-06-27 21:26:07 -07001773// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1774bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1775 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1776 bool soundTriggerSupportsConcurrentCapture = false;
1777 unsigned int numModules = 0;
1778 struct sound_trigger_module_descriptor* nModules = NULL;
1779
1780 status_t status = SoundTrigger::listModules(nModules, &numModules);
1781 if (status == NO_ERROR && numModules != 0) {
1782 nModules = (struct sound_trigger_module_descriptor*) calloc(
1783 numModules, sizeof(struct sound_trigger_module_descriptor));
1784 if (nModules == NULL) {
1785 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1786 // ram the next time this function is called.
1787 ALOGE("Failed to allocate buffer for module descriptors");
1788 return false;
1789 }
1790
1791 status = SoundTrigger::listModules(nModules, &numModules);
1792 if (status == NO_ERROR) {
1793 soundTriggerSupportsConcurrentCapture = true;
1794 for (size_t i = 0; i < numModules; ++i) {
1795 soundTriggerSupportsConcurrentCapture &=
1796 nModules[i].properties.concurrent_capture;
1797 }
1798 }
1799 free(nModules);
1800 }
1801 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1802 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1803 }
1804 return mSoundTriggerSupportsConcurrentCapture;
1805}
1806
Eric Laurentfb66dd92016-01-28 18:32:03 -08001807
Eric Laurent4dc68062014-07-28 17:26:49 -07001808status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001809 audio_session_t session,
1810 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001811{
1812 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001813 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001814 ssize_t index = mInputs.indexOfKey(input);
1815 if (index < 0) {
1816 ALOGW("startInput() unknown input %d", input);
1817 return BAD_VALUE;
1818 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001820
Eric Laurent599c7582015-12-07 18:05:55 -08001821 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1822 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001823 ALOGW("startInput() unknown session %d on input %d", session, input);
1824 return BAD_VALUE;
1825 }
1826
Eric Laurent74708e72017-04-07 17:13:42 -07001827// FIXME: disable concurrent capture until UI is ready
1828#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001829 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1830 ALOGW("startInput(%d) failed: other input already started", input);
1831 return INVALID_OPERATION;
1832 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001833
Eric Laurentfb66dd92016-01-28 18:32:03 -08001834 if (isInCall()) {
1835 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1836 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001837 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001838 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001839 }
Eric Laurent74708e72017-04-07 17:13:42 -07001840#else
1841 if (!is_virtual_input_device(inputDesc->mDevice)) {
1842 if (mCallTxPatch != 0 &&
1843 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1844 ALOGW("startInput(%d) failed: call in progress", input);
1845 return INVALID_OPERATION;
1846 }
1847
1848 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001849 for (const auto& activeDesc : activeInputs) {
Eric Laurent74708e72017-04-07 17:13:42 -07001850 if (is_virtual_input_device(activeDesc->mDevice)) {
1851 continue;
1852 }
1853
Eric Laurentcb4dae22017-07-01 19:39:32 -07001854 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1855 activeDesc->getId() == inputDesc->getId()) {
1856 continue;
1857 }
1858
Eric Laurent74708e72017-04-07 17:13:42 -07001859 audio_source_t activeSource = activeDesc->inputSource(true);
1860 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1861 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1862 if (activeDesc->hasPreemptedSession(session)) {
1863 ALOGW("startInput(%d) failed for HOTWORD: "
1864 "other input %d already started for HOTWORD",
1865 input, activeDesc->mIoHandle);
1866 return INVALID_OPERATION;
1867 }
1868 } else {
1869 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1870 input, activeDesc->mIoHandle);
1871 return INVALID_OPERATION;
1872 }
1873 } else {
1874 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1875 ALOGW("startInput(%d) failed: other input %d already started",
1876 input, activeDesc->mIoHandle);
1877 return INVALID_OPERATION;
1878 }
1879 }
1880 }
1881
Chris Thornton2b864642017-06-27 21:26:07 -07001882 // We only need to check if the sound trigger session supports concurrent capture if the
1883 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1884 // that's running.
1885 const bool allowConcurrentWithSoundTrigger =
1886 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1887
Eric Laurent74708e72017-04-07 17:13:42 -07001888 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001889 for (const auto& activeDesc : activeInputs) {
Eric Laurent74708e72017-04-07 17:13:42 -07001890 if (is_virtual_input_device(activeDesc->mDevice)) {
1891 continue;
1892 }
1893
Chris Thornton2b864642017-06-27 21:26:07 -07001894 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1895 continue;
1896 }
1897
Eric Laurent74708e72017-04-07 17:13:42 -07001898 audio_source_t activeSource = activeDesc->inputSource(true);
1899 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1900 AudioSessionCollection activeSessions =
1901 activeDesc->getAudioSessions(true /*activeOnly*/);
1902 audio_session_t activeSession = activeSessions.keyAt(0);
1903 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1904 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1905 sessions.add(activeSession);
1906 inputDesc->setPreemptedSessions(sessions);
1907 stopInput(activeHandle, activeSession);
1908 releaseInput(activeHandle, activeSession);
1909 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1910 input, activeDesc->mIoHandle);
1911 }
1912 }
1913 }
1914#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001915
Eric Laurent313d1e72016-01-29 09:56:57 -08001916 // increment activity count before calling getNewInputDevice() below as only active sessions
1917 // are considered for device selection
1918 audioSession->changeActiveCount(1);
1919
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001920 // Routing?
1921 mInputRoutes.incRouteActivity(session);
1922
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001923 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001924 // indicate active capture to sound trigger service if starting capture from a mic on
1925 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001926 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001927 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001928
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001929 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1930 // if input maps to a dynamic policy with an activity listener, notify of state change
1931 if ((inputDesc->mPolicyMix != NULL)
1932 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1933 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1934 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001935 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001936
Eric Laurentf7c50102016-09-30 15:19:43 -07001937 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1938 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001939 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001940 SoundTrigger::setCaptureState(true);
1941 }
1942
1943 // automatically enable the remote submix output when input is started if not
1944 // used by a policy mix of type MIX_TYPE_RECORDERS
1945 // For remote submix (a virtual device), we open only one input per capture request.
1946 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1947 String8 address = String8("");
1948 if (inputDesc->mPolicyMix == NULL) {
1949 address = String8("0");
1950 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1951 address = inputDesc->mPolicyMix->mDeviceAddress;
1952 }
1953 if (address != "") {
1954 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1955 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1956 address, "remote-submix");
1957 }
Eric Laurentc722f302014-12-10 11:21:49 -08001958 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001959 }
Eric Laurente552edb2014-03-10 17:42:56 -07001960 }
1961
Eric Laurent599c7582015-12-07 18:05:55 -08001962 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001963
Eric Laurente552edb2014-03-10 17:42:56 -07001964 return NO_ERROR;
1965}
1966
Eric Laurent4dc68062014-07-28 17:26:49 -07001967status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1968 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001969{
1970 ALOGV("stopInput() input %d", input);
1971 ssize_t index = mInputs.indexOfKey(input);
1972 if (index < 0) {
1973 ALOGW("stopInput() unknown input %d", input);
1974 return BAD_VALUE;
1975 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001976 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001977
Eric Laurent599c7582015-12-07 18:05:55 -08001978 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001979 if (index < 0) {
1980 ALOGW("stopInput() unknown session %d on input %d", session, input);
1981 return BAD_VALUE;
1982 }
1983
Eric Laurent599c7582015-12-07 18:05:55 -08001984 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001985 ALOGW("stopInput() input %d already stopped", input);
1986 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001987 }
1988
Eric Laurent599c7582015-12-07 18:05:55 -08001989 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001990
1991 // Routing?
1992 mInputRoutes.decRouteActivity(session);
1993
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001994 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001995
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001996 if (inputDesc->isActive()) {
1997 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1998 } else {
1999 // if input maps to a dynamic policy with an activity listener, notify of state change
2000 if ((inputDesc->mPolicyMix != NULL)
2001 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2002 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2003 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002004 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002005
2006 // automatically disable the remote submix output when input is stopped if not
2007 // used by a policy mix of type MIX_TYPE_RECORDERS
2008 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2009 String8 address = String8("");
2010 if (inputDesc->mPolicyMix == NULL) {
2011 address = String8("0");
2012 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2013 address = inputDesc->mPolicyMix->mDeviceAddress;
2014 }
2015 if (address != "") {
2016 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2017 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2018 address, "remote-submix");
2019 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002020 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002021
Eric Laurentf7c50102016-09-30 15:19:43 -07002022 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002023 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002024
Eric Laurentf7c50102016-09-30 15:19:43 -07002025 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2026 // primary HW module
2027 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2028 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2029 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002030 SoundTrigger::setCaptureState(false);
2031 }
2032 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002033 }
Eric Laurente552edb2014-03-10 17:42:56 -07002034 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002035 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002036}
2037
Eric Laurent4dc68062014-07-28 17:26:49 -07002038void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2039 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002040{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002041
Eric Laurente552edb2014-03-10 17:42:56 -07002042 ALOGV("releaseInput() %d", input);
2043 ssize_t index = mInputs.indexOfKey(input);
2044 if (index < 0) {
2045 ALOGW("releaseInput() releasing unknown input %d", input);
2046 return;
2047 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002048
2049 // Routing
2050 mInputRoutes.removeRoute(session);
2051
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002052 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2053 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002054
Eric Laurent599c7582015-12-07 18:05:55 -08002055 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002056 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002057 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2058 return;
2059 }
Eric Laurent599c7582015-12-07 18:05:55 -08002060
2061 if (audioSession->openCount() == 0) {
2062 ALOGW("releaseInput() invalid open count %d on session %d",
2063 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002064 return;
2065 }
Eric Laurent599c7582015-12-07 18:05:55 -08002066
2067 if (audioSession->changeOpenCount(-1) == 0) {
2068 inputDesc->removeAudioSession(session);
2069 }
2070
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002071 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002072 ALOGV("releaseInput() exit > 0");
2073 return;
2074 }
2075
Eric Laurent05b90f82014-08-27 15:32:29 -07002076 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002077 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002078 ALOGV("releaseInput() exit");
2079}
2080
Eric Laurentd4692962014-05-05 18:13:44 -07002081void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002082 bool patchRemoved = false;
2083
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002084 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002085 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002086 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002087 if (patch_index >= 0) {
2088 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002089 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002090 mAudioPatches.removeItemsAt(patch_index);
2091 patchRemoved = true;
2092 }
Eric Laurentfe231122017-11-17 17:48:06 -08002093 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002094 }
2095 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002096 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002097 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002098
2099 if (patchRemoved) {
2100 mpClientInterface->onAudioPatchListUpdate();
2101 }
Eric Laurentd4692962014-05-05 18:13:44 -07002102}
2103
Eric Laurente0720872014-03-11 09:30:41 -07002104void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002105 int indexMin,
2106 int indexMax)
2107{
2108 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002109 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002110
2111 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002112 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2113 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002114 continue;
2115 }
2116 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002117 }
Eric Laurente552edb2014-03-10 17:42:56 -07002118}
2119
Eric Laurente0720872014-03-11 09:30:41 -07002120status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002121 int index,
2122 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002123{
2124
François Gaffied1ab2bd2015-12-02 18:20:06 +01002125 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2126 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002127 return BAD_VALUE;
2128 }
2129 if (!audio_is_output_device(device)) {
2130 return BAD_VALUE;
2131 }
2132
2133 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002134 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002135
Eric Laurent1fd372e2016-04-06 14:23:53 -07002136 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002137 stream, device, index);
2138
Eric Laurent28d09f02016-03-08 10:43:05 -08002139 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002140 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2141 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002142 continue;
2143 }
2144 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2145 }
Eric Laurente552edb2014-03-10 17:42:56 -07002146
Eric Laurent1fd372e2016-04-06 14:23:53 -07002147 // update volume on all outputs and streams matching the following:
2148 // - The requested stream (or a stream matching for volume control) is active on the output
2149 // - The device (or devices) selected by the strategy corresponding to this stream includes
2150 // the requested device
2151 // - For non default requested device, currently selected device on the output is either the
2152 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002153 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2154 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002155 status_t status = NO_ERROR;
2156 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002157 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2158 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002159 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2160 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002161 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002162 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002163 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2164 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002165 continue;
2166 }
Eric Laurent794fde22016-03-11 09:50:45 -08002167 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002168 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2169 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002170 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2171 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002172 continue;
2173 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002174 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002175 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002176 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002177 applyVolume = (curDevice & curStreamDevice) != 0;
2178 } else {
2179 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002180 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002181 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002182
Eric Laurente76f29c2016-09-14 17:17:53 -07002183 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002184 //FIXME: workaround for truncated touch sounds
2185 // delayed volume change for system stream to be removed when the problem is
2186 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002187 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002188 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2189 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002190 if (volStatus != NO_ERROR) {
2191 status = volStatus;
2192 }
2193 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002194 }
Eric Laurente552edb2014-03-10 17:42:56 -07002195 }
2196 return status;
2197}
2198
Eric Laurente0720872014-03-11 09:30:41 -07002199status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002200 int *index,
2201 audio_devices_t device)
2202{
2203 if (index == NULL) {
2204 return BAD_VALUE;
2205 }
2206 if (!audio_is_output_device(device)) {
2207 return BAD_VALUE;
2208 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002209 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002210 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002211 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002212 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2213 }
François Gaffiedfd74092015-03-19 12:10:59 +01002214 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002215
François Gaffied1ab2bd2015-12-02 18:20:06 +01002216 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002217 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2218 return NO_ERROR;
2219}
2220
Eric Laurent36829f92017-04-07 19:04:42 -07002221audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002222{
2223 // select one output among several suitable for global effects.
2224 // The priority is as follows:
2225 // 1: An offloaded output. If the effect ends up not being offloadable,
2226 // AudioFlinger will invalidate the track and the offloaded output
2227 // will be closed causing the effect to be moved to a PCM output.
2228 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002229 // 3: The primary output
2230 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002231
Eric Laurent3b73df72014-03-11 09:06:29 -07002232 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002233 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002234 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Eric Laurent36829f92017-04-07 19:04:42 -07002236 if (outputs.size() == 0) {
2237 return AUDIO_IO_HANDLE_NONE;
2238 }
Eric Laurente552edb2014-03-10 17:42:56 -07002239
Eric Laurent36829f92017-04-07 19:04:42 -07002240 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2241 bool activeOnly = true;
2242
2243 while (output == AUDIO_IO_HANDLE_NONE) {
2244 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2245 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2246 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2247
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002248 for (audio_io_handle_t output : outputs) {
2249 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002250 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2251 continue;
2252 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002253 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2254 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002255 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002256 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002257 }
2258 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002259 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002260 }
2261 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002262 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002263 }
2264 }
2265 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2266 output = outputOffloaded;
2267 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2268 output = outputDeepBuffer;
2269 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2270 output = outputPrimary;
2271 } else {
2272 output = outputs[0];
2273 }
2274 activeOnly = false;
2275 }
2276
2277 if (output != mMusicEffectOutput) {
2278 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2279 mMusicEffectOutput = output;
2280 }
2281
2282 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002283 return output;
2284}
2285
Eric Laurent36829f92017-04-07 19:04:42 -07002286audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2287{
2288 return selectOutputForMusicEffects();
2289}
2290
Eric Laurente0720872014-03-11 09:30:41 -07002291status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002292 audio_io_handle_t io,
2293 uint32_t strategy,
2294 int session,
2295 int id)
2296{
2297 ssize_t index = mOutputs.indexOfKey(io);
2298 if (index < 0) {
2299 index = mInputs.indexOfKey(io);
2300 if (index < 0) {
2301 ALOGW("registerEffect() unknown io %d", io);
2302 return INVALID_OPERATION;
2303 }
2304 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002305 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002306}
2307
Eric Laurentc75307b2015-03-17 15:29:32 -07002308bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2309{
Eric Laurent28d09f02016-03-08 10:43:05 -08002310 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002311 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2312 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002313 continue;
2314 }
2315 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2316 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002317 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002318}
2319
2320bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2321{
2322 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2323}
2324
Eric Laurente0720872014-03-11 09:30:41 -07002325bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002326{
2327 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002328 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002329 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002330 return true;
2331 }
2332 }
2333 return false;
2334}
2335
Eric Laurent275e8e92014-11-30 15:14:47 -08002336// Register a list of custom mixes with their attributes and format.
2337// When a mix is registered, corresponding input and output profiles are
2338// added to the remote submix hw module. The profile contains only the
2339// parameters (sampling rate, format...) specified by the mix.
2340// The corresponding input remote submix device is also connected.
2341//
2342// When a remote submix device is connected, the address is checked to select the
2343// appropriate profile and the corresponding input or output stream is opened.
2344//
2345// When capture starts, getInputForAttr() will:
2346// - 1 look for a mix matching the address passed in attribtutes tags if any
2347// - 2 if none found, getDeviceForInputSource() will:
2348// - 2.1 look for a mix matching the attributes source
2349// - 2.2 if none found, default to device selection by policy rules
2350// At this time, the corresponding output remote submix device is also connected
2351// and active playback use cases can be transferred to this mix if needed when reconnecting
2352// after AudioTracks are invalidated
2353//
2354// When playback starts, getOutputForAttr() will:
2355// - 1 look for a mix matching the address passed in attribtutes tags if any
2356// - 2 if none found, look for a mix matching the attributes usage
2357// - 3 if none found, default to device and output selection by policy rules.
2358
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002359status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002360{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002361 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2362 status_t res = NO_ERROR;
2363
2364 sp<HwModule> rSubmixModule;
2365 // examine each mix's route type
2366 for (size_t i = 0; i < mixes.size(); i++) {
2367 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2368 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2369 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002370 break;
2371 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002372 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002373 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002374 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002375 rSubmixModule = mHwModules.getModuleFromName(
2376 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2377 if (rSubmixModule == 0) {
2378 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2379 i);
2380 res = INVALID_OPERATION;
2381 break;
2382 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002383 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002384
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002385 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002386
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002387 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002388 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002389 res = INVALID_OPERATION;
2390 break;
2391 }
2392 audio_config_t outputConfig = mixes[i].mFormat;
2393 audio_config_t inputConfig = mixes[i].mFormat;
2394 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2395 // stereo and let audio flinger do the channel conversion if needed.
2396 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2397 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2398 rSubmixModule->addOutputProfile(address, &outputConfig,
2399 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2400 rSubmixModule->addInputProfile(address, &inputConfig,
2401 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002402
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002403 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2404 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2405 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2406 address.string(), "remote-submix");
2407 } else {
2408 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2409 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2410 address.string(), "remote-submix");
2411 }
2412 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002413 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002414 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002415 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2416 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002417
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002418 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002419 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2420 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2421 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2422 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2423 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2424 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002425 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2426 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002427 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2428 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002429 } else {
2430 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002431 }
2432 break;
2433 }
2434 }
2435
2436 if (res != NO_ERROR) {
2437 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002438 i, device, address.string());
2439 res = INVALID_OPERATION;
2440 break;
2441 } else if (!foundOutput) {
2442 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2443 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002444 res = INVALID_OPERATION;
2445 break;
2446 }
Eric Laurentc722f302014-12-10 11:21:49 -08002447 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002448 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002449 if (res != NO_ERROR) {
2450 unregisterPolicyMixes(mixes);
2451 }
2452 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002453}
2454
2455status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2456{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002457 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002458 status_t res = NO_ERROR;
2459 sp<HwModule> rSubmixModule;
2460 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002461 for (const auto& mix : mixes) {
2462 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002463
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002464 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002465 rSubmixModule = mHwModules.getModuleFromName(
2466 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2467 if (rSubmixModule == 0) {
2468 res = INVALID_OPERATION;
2469 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002470 }
2471 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002472
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002473 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002474
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2476 res = INVALID_OPERATION;
2477 continue;
2478 }
2479
2480 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2482 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2483 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2484 address.string(), "remote-submix");
2485 }
2486 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2487 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2488 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2489 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2490 address.string(), "remote-submix");
2491 }
2492 rSubmixModule->removeOutputProfile(address);
2493 rSubmixModule->removeInputProfile(address);
2494
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002495 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2496 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 res = INVALID_OPERATION;
2498 continue;
2499 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002500 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002501 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002502 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002503}
2504
Eric Laurente552edb2014-03-10 17:42:56 -07002505
Eric Laurente0720872014-03-11 09:30:41 -07002506status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002507{
2508 const size_t SIZE = 256;
2509 char buffer[SIZE];
2510 String8 result;
2511
2512 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2513 result.append(buffer);
2514
Eric Laurent87ffa392015-05-22 10:32:38 -07002515 snprintf(buffer, SIZE, " Primary Output: %d\n",
2516 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002517 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002518 std::string stateLiteral;
2519 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2520 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002521 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002522 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002523 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002524 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002525 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002526 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002527 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002528 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002529 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002530 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002531 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002532 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002533 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002534 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002535 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002536 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2537 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2538 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002539 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2540 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002541 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2542 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002543
François Gaffie2110e042015-03-24 08:41:51 +01002544 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002545
François Gaffie112b0af2015-11-19 16:13:25 +01002546 mAvailableOutputDevices.dump(fd, String8("Available output"));
2547 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002548 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002549 mOutputs.dump(fd);
2550 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002551 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002552 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002553 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002554 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002555
2556 return NO_ERROR;
2557}
2558
2559// This function checks for the parameters which can be offloaded.
2560// This can be enhanced depending on the capability of the DSP and policy
2561// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002562bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002563{
2564 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002565 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002566 offloadInfo.sample_rate, offloadInfo.channel_mask,
2567 offloadInfo.format,
2568 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2569 offloadInfo.has_video);
2570
Andy Hung2ddee192015-12-18 17:34:44 -08002571 if (mMasterMono) {
2572 return false; // no offloading if mono is set.
2573 }
2574
Eric Laurente552edb2014-03-10 17:42:56 -07002575 // Check if offload has been disabled
2576 char propValue[PROPERTY_VALUE_MAX];
2577 if (property_get("audio.offload.disable", propValue, "0")) {
2578 if (atoi(propValue) != 0) {
2579 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2580 return false;
2581 }
2582 }
2583
2584 // Check if stream type is music, then only allow offload as of now.
2585 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2586 {
2587 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2588 return false;
2589 }
2590
2591 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002592 const bool allowOffloadWithVideo =
2593 property_get_bool("audio.offload.video", false /* default_value */);
2594 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002595 ALOGV("isOffloadSupported: has_video == true, returning false");
2596 return false;
2597 }
2598
2599 //If duration is less than minimum value defined in property, return false
2600 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2601 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2602 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2603 return false;
2604 }
2605 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2606 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2607 return false;
2608 }
2609
2610 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2611 // creating an offloaded track and tearing it down immediately after start when audioflinger
2612 // detects there is an active non offloadable effect.
2613 // FIXME: We should check the audio session here but we do not have it in this context.
2614 // This may prevent offloading in rare situations where effects are left active by apps
2615 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002616 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002617 return false;
2618 }
2619
2620 // See if there is a profile to support this.
2621 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002622 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002623 offloadInfo.sample_rate,
2624 offloadInfo.format,
2625 offloadInfo.channel_mask,
2626 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002627 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2628 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002629}
2630
Eric Laurent6a94d692014-05-20 11:18:06 -07002631status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2632 audio_port_type_t type,
2633 unsigned int *num_ports,
2634 struct audio_port *ports,
2635 unsigned int *generation)
2636{
2637 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2638 generation == NULL) {
2639 return BAD_VALUE;
2640 }
2641 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2642 if (ports == NULL) {
2643 *num_ports = 0;
2644 }
2645
2646 size_t portsWritten = 0;
2647 size_t portsMax = *num_ports;
2648 *num_ports = 0;
2649 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002650 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2651 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002652 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002653 for (const auto& dev : mAvailableOutputDevices) {
2654 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002655 continue;
2656 }
2657 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002658 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002659 }
2660 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002661 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002662 }
2663 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002664 for (const auto& dev : mAvailableInputDevices) {
2665 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002666 continue;
2667 }
2668 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002669 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002670 }
2671 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002672 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002673 }
2674 }
2675 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2676 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2677 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2678 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2679 }
2680 *num_ports += mInputs.size();
2681 }
2682 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002683 size_t numOutputs = 0;
2684 for (size_t i = 0; i < mOutputs.size(); i++) {
2685 if (!mOutputs[i]->isDuplicated()) {
2686 numOutputs++;
2687 if (portsWritten < portsMax) {
2688 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2689 }
2690 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002691 }
Eric Laurent84c70242014-06-23 08:46:27 -07002692 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002693 }
2694 }
2695 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002696 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002697 return NO_ERROR;
2698}
2699
2700status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2701{
2702 return NO_ERROR;
2703}
2704
Eric Laurent6a94d692014-05-20 11:18:06 -07002705status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2706 audio_patch_handle_t *handle,
2707 uid_t uid)
2708{
2709 ALOGV("createAudioPatch()");
2710
2711 if (handle == NULL || patch == NULL) {
2712 return BAD_VALUE;
2713 }
2714 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2715
Eric Laurent874c42872014-08-08 15:13:39 -07002716 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2717 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2718 return BAD_VALUE;
2719 }
2720 // only one source per audio patch supported for now
2721 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002722 return INVALID_OPERATION;
2723 }
Eric Laurent874c42872014-08-08 15:13:39 -07002724
2725 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002726 return INVALID_OPERATION;
2727 }
Eric Laurent874c42872014-08-08 15:13:39 -07002728 for (size_t i = 0; i < patch->num_sinks; i++) {
2729 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2730 return INVALID_OPERATION;
2731 }
2732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002733
2734 sp<AudioPatch> patchDesc;
2735 ssize_t index = mAudioPatches.indexOfKey(*handle);
2736
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2738 patch->sources[0].role,
2739 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002740#if LOG_NDEBUG == 0
2741 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002742 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002743 patch->sinks[i].role,
2744 patch->sinks[i].type);
2745 }
2746#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002747
2748 if (index >= 0) {
2749 patchDesc = mAudioPatches.valueAt(index);
2750 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2751 mUidCached, patchDesc->mUid, uid);
2752 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2753 return INVALID_OPERATION;
2754 }
2755 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002756 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 }
2758
2759 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002760 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002761 if (outputDesc == NULL) {
2762 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2763 return BAD_VALUE;
2764 }
Eric Laurent84c70242014-06-23 08:46:27 -07002765 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2766 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002767 if (patchDesc != 0) {
2768 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2769 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2770 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2771 return BAD_VALUE;
2772 }
2773 }
Eric Laurent874c42872014-08-08 15:13:39 -07002774 DeviceVector devices;
2775 for (size_t i = 0; i < patch->num_sinks; i++) {
2776 // Only support mix to devices connection
2777 // TODO add support for mix to mix connection
2778 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2779 ALOGV("createAudioPatch() source mix but sink is not a device");
2780 return INVALID_OPERATION;
2781 }
2782 sp<DeviceDescriptor> devDesc =
2783 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2784 if (devDesc == 0) {
2785 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2786 return BAD_VALUE;
2787 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002788
François Gaffie53615e22015-03-19 09:24:12 +01002789 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002790 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002791 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002792 NULL, // updatedSamplingRate
2793 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002794 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002795 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002796 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002797 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002798 ALOGV("createAudioPatch() profile not supported for device %08x",
2799 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002800 return INVALID_OPERATION;
2801 }
2802 devices.add(devDesc);
2803 }
2804 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 return INVALID_OPERATION;
2806 }
Eric Laurent874c42872014-08-08 15:13:39 -07002807
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 // TODO: reconfigure output format and channels here
2809 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002810 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002811 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 index = mAudioPatches.indexOfKey(*handle);
2813 if (index >= 0) {
2814 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2815 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2816 }
2817 patchDesc = mAudioPatches.valueAt(index);
2818 patchDesc->mUid = uid;
2819 ALOGV("createAudioPatch() success");
2820 } else {
2821 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2822 return INVALID_OPERATION;
2823 }
2824 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2825 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2826 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002827 // only one sink supported when connecting an input device to a mix
2828 if (patch->num_sinks > 1) {
2829 return INVALID_OPERATION;
2830 }
François Gaffie53615e22015-03-19 09:24:12 +01002831 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 if (inputDesc == NULL) {
2833 return BAD_VALUE;
2834 }
2835 if (patchDesc != 0) {
2836 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2837 return BAD_VALUE;
2838 }
2839 }
2840 sp<DeviceDescriptor> devDesc =
2841 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2842 if (devDesc == 0) {
2843 return BAD_VALUE;
2844 }
2845
François Gaffie53615e22015-03-19 09:24:12 +01002846 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002847 devDesc->mAddress,
2848 patch->sinks[0].sample_rate,
2849 NULL, /*updatedSampleRate*/
2850 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002851 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002852 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002853 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002854 // FIXME for the parameter type,
2855 // and the NONE
2856 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002857 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 return INVALID_OPERATION;
2859 }
2860 // TODO: reconfigure output format and channels here
2861 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002862 devDesc->type(), inputDesc->mIoHandle);
2863 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002864 index = mAudioPatches.indexOfKey(*handle);
2865 if (index >= 0) {
2866 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2867 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2868 }
2869 patchDesc = mAudioPatches.valueAt(index);
2870 patchDesc->mUid = uid;
2871 ALOGV("createAudioPatch() success");
2872 } else {
2873 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2874 return INVALID_OPERATION;
2875 }
2876 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2877 // device to device connection
2878 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002879 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 return BAD_VALUE;
2881 }
2882 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002883 sp<DeviceDescriptor> srcDeviceDesc =
2884 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002885 if (srcDeviceDesc == 0) {
2886 return BAD_VALUE;
2887 }
Eric Laurent874c42872014-08-08 15:13:39 -07002888
Eric Laurent6a94d692014-05-20 11:18:06 -07002889 //update source and sink with our own data as the data passed in the patch may
2890 // be incomplete.
2891 struct audio_patch newPatch = *patch;
2892 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002893
Eric Laurent874c42872014-08-08 15:13:39 -07002894 for (size_t i = 0; i < patch->num_sinks; i++) {
2895 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2896 ALOGV("createAudioPatch() source device but one sink is not a device");
2897 return INVALID_OPERATION;
2898 }
2899
2900 sp<DeviceDescriptor> sinkDeviceDesc =
2901 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2902 if (sinkDeviceDesc == 0) {
2903 return BAD_VALUE;
2904 }
2905 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2906
Eric Laurent3bcf8592015-04-03 12:13:24 -07002907 // create a software bridge in PatchPanel if:
2908 // - source and sink devices are on differnt HW modules OR
2909 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002910 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002911 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002912 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002913 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002914 return INVALID_OPERATION;
2915 }
Eric Laurent874c42872014-08-08 15:13:39 -07002916 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002917 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002918 // if the sink device is reachable via an opened output stream, request to go via
2919 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002920 audio_io_handle_t output = selectOutput(outputs,
2921 AUDIO_OUTPUT_FLAG_NONE,
2922 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002923 if (output != AUDIO_IO_HANDLE_NONE) {
2924 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2925 if (outputDesc->isDuplicated()) {
2926 return INVALID_OPERATION;
2927 }
2928 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002929 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002930 newPatch.num_sources = 2;
2931 }
Eric Laurent83b88082014-06-20 18:31:16 -07002932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 }
2934 // TODO: check from routing capabilities in config file and other conflicting patches
2935
2936 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2937 if (index >= 0) {
2938 afPatchHandle = patchDesc->mAfPatchHandle;
2939 }
2940
2941 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2942 &afPatchHandle,
2943 0);
2944 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2945 status, afPatchHandle);
2946 if (status == NO_ERROR) {
2947 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002948 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 addAudioPatch(patchDesc->mHandle, patchDesc);
2950 } else {
2951 patchDesc->mPatch = newPatch;
2952 }
2953 patchDesc->mAfPatchHandle = afPatchHandle;
2954 *handle = patchDesc->mHandle;
2955 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002956 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002957 } else {
2958 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2959 status);
2960 return INVALID_OPERATION;
2961 }
2962 } else {
2963 return BAD_VALUE;
2964 }
2965 } else {
2966 return BAD_VALUE;
2967 }
2968 return NO_ERROR;
2969}
2970
2971status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2972 uid_t uid)
2973{
2974 ALOGV("releaseAudioPatch() patch %d", handle);
2975
2976 ssize_t index = mAudioPatches.indexOfKey(handle);
2977
2978 if (index < 0) {
2979 return BAD_VALUE;
2980 }
2981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2982 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2983 mUidCached, patchDesc->mUid, uid);
2984 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2985 return INVALID_OPERATION;
2986 }
2987
2988 struct audio_patch *patch = &patchDesc->mPatch;
2989 patchDesc->mUid = mUidCached;
2990 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002991 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002992 if (outputDesc == NULL) {
2993 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2994 return BAD_VALUE;
2995 }
2996
Eric Laurentc75307b2015-03-17 15:29:32 -07002997 setOutputDevice(outputDesc,
2998 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002999 true,
3000 0,
3001 NULL);
3002 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3003 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003004 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 if (inputDesc == NULL) {
3006 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3007 return BAD_VALUE;
3008 }
3009 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003010 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 true,
3012 NULL);
3013 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3015 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3016 status, patchDesc->mAfPatchHandle);
3017 removeAudioPatch(patchDesc->mHandle);
3018 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003019 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 } else {
3021 return BAD_VALUE;
3022 }
3023 } else {
3024 return BAD_VALUE;
3025 }
3026 return NO_ERROR;
3027}
3028
3029status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3030 struct audio_patch *patches,
3031 unsigned int *generation)
3032{
François Gaffie53615e22015-03-19 09:24:12 +01003033 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003034 return BAD_VALUE;
3035 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003036 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003037 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003038}
3039
Eric Laurente1715a42014-05-20 11:30:42 -07003040status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003041{
Eric Laurente1715a42014-05-20 11:30:42 -07003042 ALOGV("setAudioPortConfig()");
3043
3044 if (config == NULL) {
3045 return BAD_VALUE;
3046 }
3047 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3048 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003049 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3050 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003051 }
3052
Eric Laurenta121f902014-06-03 13:32:54 -07003053 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003054 if (config->type == AUDIO_PORT_TYPE_MIX) {
3055 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003056 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003057 if (outputDesc == NULL) {
3058 return BAD_VALUE;
3059 }
Eric Laurent84c70242014-06-23 08:46:27 -07003060 ALOG_ASSERT(!outputDesc->isDuplicated(),
3061 "setAudioPortConfig() called on duplicated output %d",
3062 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003063 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003064 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003065 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003066 if (inputDesc == NULL) {
3067 return BAD_VALUE;
3068 }
Eric Laurenta121f902014-06-03 13:32:54 -07003069 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003070 } else {
3071 return BAD_VALUE;
3072 }
3073 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3074 sp<DeviceDescriptor> deviceDesc;
3075 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3076 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3077 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3078 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3079 } else {
3080 return BAD_VALUE;
3081 }
3082 if (deviceDesc == NULL) {
3083 return BAD_VALUE;
3084 }
Eric Laurenta121f902014-06-03 13:32:54 -07003085 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003086 } else {
3087 return BAD_VALUE;
3088 }
3089
Eric Laurenta121f902014-06-03 13:32:54 -07003090 struct audio_port_config backupConfig;
3091 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3092 if (status == NO_ERROR) {
3093 struct audio_port_config newConfig;
3094 audioPortConfig->toAudioPortConfig(&newConfig, config);
3095 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003096 }
Eric Laurenta121f902014-06-03 13:32:54 -07003097 if (status != NO_ERROR) {
3098 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003099 }
Eric Laurente1715a42014-05-20 11:30:42 -07003100
3101 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003102}
3103
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003104void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3105{
Eric Laurentd60560a2015-04-10 11:31:20 -07003106 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003107 clearAudioPatches(uid);
3108 clearSessionRoutes(uid);
3109}
3110
Eric Laurent6a94d692014-05-20 11:18:06 -07003111void AudioPolicyManager::clearAudioPatches(uid_t uid)
3112{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003113 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003114 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3115 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003116 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 }
3118 }
3119}
3120
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003121void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3122 audio_io_handle_t ouptutToSkip)
3123{
3124 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3125 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3126 for (size_t j = 0; j < mOutputs.size(); j++) {
3127 if (mOutputs.keyAt(j) == ouptutToSkip) {
3128 continue;
3129 }
3130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3131 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3132 continue;
3133 }
3134 // If the default device for this strategy is on another output mix,
3135 // invalidate all tracks in this strategy to force re connection.
3136 // Otherwise select new device on the output mix.
3137 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003138 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003139 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3140 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3141 }
3142 }
3143 } else {
3144 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3145 setOutputDevice(outputDesc, newDevice, false);
3146 }
3147 }
3148}
3149
3150void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3151{
3152 // remove output routes associated with this uid
3153 SortedVector<routing_strategy> affectedStrategies;
3154 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3155 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3156 if (route->mUid == uid) {
3157 mOutputRoutes.removeItemsAt(i);
3158 if (route->mDeviceDescriptor != 0) {
3159 affectedStrategies.add(getStrategy(route->mStreamType));
3160 }
3161 }
3162 }
3163 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003164 for (const auto& strategy : affectedStrategies) {
3165 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003166 }
3167
3168 // remove input routes associated with this uid
3169 SortedVector<audio_source_t> affectedSources;
3170 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3171 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3172 if (route->mUid == uid) {
3173 mInputRoutes.removeItemsAt(i);
3174 if (route->mDeviceDescriptor != 0) {
3175 affectedSources.add(route->mSource);
3176 }
3177 }
3178 }
3179 // reroute inputs if necessary
3180 SortedVector<audio_io_handle_t> inputsToClose;
3181 for (size_t i = 0; i < mInputs.size(); i++) {
3182 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003183 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003184 inputsToClose.add(inputDesc->mIoHandle);
3185 }
3186 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003187 for (const auto& input : inputsToClose) {
3188 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003189 }
3190}
3191
Eric Laurentd60560a2015-04-10 11:31:20 -07003192void AudioPolicyManager::clearAudioSources(uid_t uid)
3193{
3194 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3195 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3196 if (sourceDesc->mUid == uid) {
3197 stopAudioSource(mAudioSources.keyAt(i));
3198 }
3199 }
3200}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003201
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003202status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3203 audio_io_handle_t *ioHandle,
3204 audio_devices_t *device)
3205{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003206 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3207 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003208 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003209
François Gaffiedf372692015-03-19 10:43:27 +01003210 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003211}
3212
Eric Laurentd60560a2015-04-10 11:31:20 -07003213status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3214 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003215 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003216 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003217{
Eric Laurentd60560a2015-04-10 11:31:20 -07003218 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3219 if (source == NULL || attributes == NULL || handle == NULL) {
3220 return BAD_VALUE;
3221 }
3222
Glenn Kasten559d4392016-03-29 13:42:57 -07003223 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003224
3225 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3226 source->type != AUDIO_PORT_TYPE_DEVICE) {
3227 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3228 return INVALID_OPERATION;
3229 }
3230
3231 sp<DeviceDescriptor> srcDeviceDesc =
3232 mAvailableInputDevices.getDevice(source->ext.device.type,
3233 String8(source->ext.device.address));
3234 if (srcDeviceDesc == 0) {
3235 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3236 return BAD_VALUE;
3237 }
3238 sp<AudioSourceDescriptor> sourceDesc =
3239 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3240
3241 struct audio_patch dummyPatch;
3242 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3243 sourceDesc->mPatchDesc = patchDesc;
3244
3245 status_t status = connectAudioSource(sourceDesc);
3246 if (status == NO_ERROR) {
3247 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3248 *handle = sourceDesc->getHandle();
3249 }
3250 return status;
3251}
3252
3253status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3254{
3255 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3256
3257 // make sure we only have one patch per source.
3258 disconnectAudioSource(sourceDesc);
3259
3260 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003261 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003262 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3263
3264 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3265 sp<DeviceDescriptor> sinkDeviceDesc =
3266 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3267
3268 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3269 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3270
3271 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3272 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003273 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003274 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3275 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3276 // create patch between src device and output device
3277 // create Hwoutput and add to mHwOutputs
3278 } else {
3279 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3280 audio_io_handle_t output =
3281 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3282 if (output == AUDIO_IO_HANDLE_NONE) {
3283 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3284 return INVALID_OPERATION;
3285 }
3286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3287 if (outputDesc->isDuplicated()) {
3288 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3289 return INVALID_OPERATION;
3290 }
3291 // create a special patch with no sink and two sources:
3292 // - the second source indicates to PatchPanel through which output mix this patch should
3293 // be connected as well as the stream type for volume control
3294 // - the sink is defined by whatever output device is currently selected for the output
3295 // though which this patch is routed.
3296 patch->num_sinks = 0;
3297 patch->num_sources = 2;
3298 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3299 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3300 patch->sources[1].ext.mix.usecase.stream = stream;
3301 status_t status = mpClientInterface->createAudioPatch(patch,
3302 &afPatchHandle,
3303 0);
3304 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3305 status, afPatchHandle);
3306 if (status != NO_ERROR) {
3307 ALOGW("%s patch panel could not connect device patch, error %d",
3308 __FUNCTION__, status);
3309 return INVALID_OPERATION;
3310 }
3311 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003312 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003313
3314 if (status != NO_ERROR) {
3315 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3316 return status;
3317 }
3318 sourceDesc->mSwOutput = outputDesc;
3319 if (delayMs != 0) {
3320 usleep(delayMs * 1000);
3321 }
3322 }
3323
3324 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3325 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3326
3327 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003328}
3329
Glenn Kasten559d4392016-03-29 13:42:57 -07003330status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003331{
Eric Laurentd60560a2015-04-10 11:31:20 -07003332 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3333 ALOGV("%s handle %d", __FUNCTION__, handle);
3334 if (sourceDesc == 0) {
3335 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3336 return BAD_VALUE;
3337 }
3338 status_t status = disconnectAudioSource(sourceDesc);
3339
3340 mAudioSources.removeItem(handle);
3341 return status;
3342}
3343
Andy Hung2ddee192015-12-18 17:34:44 -08003344status_t AudioPolicyManager::setMasterMono(bool mono)
3345{
3346 if (mMasterMono == mono) {
3347 return NO_ERROR;
3348 }
3349 mMasterMono = mono;
3350 // if enabling mono we close all offloaded devices, which will invalidate the
3351 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3352 // for recreating the new AudioTrack as non-offloaded PCM.
3353 //
3354 // If disabling mono, we leave all tracks as is: we don't know which clients
3355 // and tracks are able to be recreated as offloaded. The next "song" should
3356 // play back offloaded.
3357 if (mMasterMono) {
3358 Vector<audio_io_handle_t> offloaded;
3359 for (size_t i = 0; i < mOutputs.size(); ++i) {
3360 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3361 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3362 offloaded.push(desc->mIoHandle);
3363 }
3364 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003365 for (const auto& handle : offloaded) {
3366 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003367 }
3368 }
3369 // update master mono for all remaining outputs
3370 for (size_t i = 0; i < mOutputs.size(); ++i) {
3371 updateMono(mOutputs.keyAt(i));
3372 }
3373 return NO_ERROR;
3374}
3375
3376status_t AudioPolicyManager::getMasterMono(bool *mono)
3377{
3378 *mono = mMasterMono;
3379 return NO_ERROR;
3380}
3381
Eric Laurentac9cef52017-06-09 15:46:26 -07003382float AudioPolicyManager::getStreamVolumeDB(
3383 audio_stream_type_t stream, int index, audio_devices_t device)
3384{
3385 return computeVolume(stream, index, device);
3386}
3387
Eric Laurentd60560a2015-04-10 11:31:20 -07003388status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3389{
3390 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3391
3392 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3393 if (patchDesc == 0) {
3394 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3395 sourceDesc->mPatchDesc->mHandle);
3396 return BAD_VALUE;
3397 }
3398 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3399
Eric Laurent28d09f02016-03-08 10:43:05 -08003400 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3402 if (swOutputDesc != 0) {
3403 stopSource(swOutputDesc, stream, false);
3404 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3405 } else {
3406 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3407 if (hwOutputDesc != 0) {
3408 // release patch between src device and output device
3409 // close Hwoutput and remove from mHwOutputs
3410 } else {
3411 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3412 }
3413 }
3414 return NO_ERROR;
3415}
3416
3417sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3418 audio_io_handle_t output, routing_strategy strategy)
3419{
3420 sp<AudioSourceDescriptor> source;
3421 for (size_t i = 0; i < mAudioSources.size(); i++) {
3422 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3423 routing_strategy sourceStrategy =
3424 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3425 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3426 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3427 source = sourceDesc;
3428 break;
3429 }
3430 }
3431 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003432}
3433
Eric Laurente552edb2014-03-10 17:42:56 -07003434// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003435// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003436// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003437uint32_t AudioPolicyManager::nextAudioPortGeneration()
3438{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003439 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003440}
3441
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003442#ifdef USE_XML_AUDIO_POLICY_CONF
3443// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3444static const char *kConfigLocationList[] =
3445 {"/odm/etc", "/vendor/etc", "/system/etc"};
3446static const int kConfigLocationListSize =
3447 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3448
3449static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3450 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3451 status_t ret;
3452
3453 for (int i = 0; i < kConfigLocationListSize; i++) {
3454 PolicySerializer serializer;
3455 snprintf(audioPolicyXmlConfigFile,
3456 sizeof(audioPolicyXmlConfigFile),
3457 "%s/%s",
3458 kConfigLocationList[i],
3459 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3460 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3461 if (ret == NO_ERROR) {
3462 break;
3463 }
3464 }
3465 return ret;
3466}
3467#endif
3468
Eric Laurente0720872014-03-11 09:30:41 -07003469AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003470 :
Eric Laurente552edb2014-03-10 17:42:56 -07003471 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003472 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003473 mAudioPortGeneration(1),
3474 mBeaconMuteRefCount(0),
3475 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003476 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003477 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003478 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003479 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3480 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003481{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003482 mUidCached = getuid();
3483 mpClientInterface = clientInterface;
3484
3485 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3486 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3487 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3488 bool speakerDrcEnabled = false;
3489
3490#ifdef USE_XML_AUDIO_POLICY_CONF
3491 mVolumeCurves = new VolumeCurvesCollection();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003492 AudioPolicyConfig config(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
François Gaffied1ab2bd2015-12-02 18:20:06 +01003493 mDefaultOutputDevice, speakerDrcEnabled,
3494 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003495 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003496#else
3497 mVolumeCurves = new StreamDescriptorCollection();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003498 AudioPolicyConfig config(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
François Gaffied1ab2bd2015-12-02 18:20:06 +01003499 mDefaultOutputDevice, speakerDrcEnabled);
3500 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3501 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3502#endif
3503 ALOGE("could not load audio policy configuration file, setting defaults");
3504 config.setDefault();
3505 }
3506 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3507 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3508
3509 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003510 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3511 if (!engineInstance) {
3512 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3513 return;
3514 }
3515 // Retrieve the Policy Manager Interface
3516 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3517 if (mEngine == NULL) {
3518 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3519 return;
3520 }
3521 mEngine->setObserver(this);
3522 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003523 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003524 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3525
Eric Laurent3a4311c2014-03-17 12:00:47 -07003526 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003527 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003528 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3529 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003530 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003531 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003532 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3533 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003534 continue;
3535 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003536 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003537 // open all output streams needed to access attached devices
3538 // except for direct output streams that are only opened when they are actually
3539 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003540 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003541 for (const auto& outProfile : hwModule->getOutputProfiles()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003542 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003543 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003544 continue;
3545 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003546 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003547 mTtsOutputAvailable = true;
3548 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003549
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003550 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003551 continue;
3552 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003553 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003554 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3555 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003556 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003557 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003558 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003559 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003560 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003561 if ((profileType & outputDeviceTypes) == 0) {
3562 continue;
3563 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003564 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3565 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003566 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3567 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3568 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3569 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003570 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003571 status_t status = outputDesc->open(nullptr, profileType, address,
3572 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003573
3574 if (status != NO_ERROR) {
3575 ALOGW("Cannot open output stream for device %08x on hw module %s",
3576 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003577 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003578 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003579 for (const auto& dev : supportedDevices) {
3580 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003581 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003582 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003583 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003584 }
3585 }
3586 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003587 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003588 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003589 }
3590 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003591 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003592 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003593 true,
3594 0,
3595 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003596 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003597 }
Eric Laurente552edb2014-03-10 17:42:56 -07003598 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003599 // open input streams needed to access attached devices to validate
3600 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003601 for (const auto& inProfile : hwModule->getInputProfiles()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003602 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003603 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003604 continue;
3605 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003606 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003607 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003608 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3609
Eric Laurentd78f1532014-09-16 16:38:20 -07003610 if ((profileType & inputDeviceTypes) == 0) {
3611 continue;
3612 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003613 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003614 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003615
Eric Laurentd78f1532014-09-16 16:38:20 -07003616 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003617 status_t status = inputDesc->open(nullptr,
3618 profileType,
3619 String8(""),
3620 AUDIO_SOURCE_MIC,
3621 AUDIO_INPUT_FLAG_NONE,
3622 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003623
3624 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003625 for (const auto& dev : inProfile->getSupportedDevices()) {
3626 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003627 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003628 if (index >= 0) {
3629 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3630 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003631 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003632 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003633 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003634 }
3635 }
Eric Laurentfe231122017-11-17 17:48:06 -08003636 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003637 } else {
3638 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003639 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003640 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003641 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003642 }
3643 }
3644 // make sure all attached devices have been allocated a unique ID
3645 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003646 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003647 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003648 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3649 continue;
3650 }
François Gaffie2110e042015-03-24 08:41:51 +01003651 // The device is now validated and can be appended to the available devices of the engine
3652 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3653 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003654 i++;
3655 }
3656 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003657 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003658 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003659 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3660 continue;
3661 }
François Gaffie2110e042015-03-24 08:41:51 +01003662 // The device is now validated and can be appended to the available devices of the engine
3663 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3664 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003665 i++;
3666 }
3667 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003668 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003669 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003670 }
Eric Laurente552edb2014-03-10 17:42:56 -07003671
3672 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3673
3674 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -07003675}
3676
Eric Laurente0720872014-03-11 09:30:41 -07003677AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003678{
Eric Laurente552edb2014-03-10 17:42:56 -07003679 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003680 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003681 }
3682 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003683 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003684 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003685 mAvailableOutputDevices.clear();
3686 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003687 mOutputs.clear();
3688 mInputs.clear();
3689 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003690 mHwModulesAll.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003691}
3692
Eric Laurente0720872014-03-11 09:30:41 -07003693status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003694{
Eric Laurent87ffa392015-05-22 10:32:38 -07003695 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003696}
3697
Eric Laurente552edb2014-03-10 17:42:56 -07003698// ---
3699
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003700void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003701{
Eric Laurent1c333e22014-05-20 10:48:17 -07003702 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003703 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003704 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003706}
3707
François Gaffie53615e22015-03-19 09:24:12 +01003708void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3709{
3710 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07003711 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01003712}
3713
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003714void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003715{
Eric Laurent1c333e22014-05-20 10:48:17 -07003716 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003717 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003718}
Eric Laurente552edb2014-03-10 17:42:56 -07003719
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003720void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003721 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003722 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003723 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003724 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003725 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003726 if (devDesc != 0) {
3727 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3728 desc->mIoHandle, address.string());
3729 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003730 }
3731}
3732
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003733status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003734 audio_policy_dev_state_t state,
3735 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003736 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003737{
François Gaffie53615e22015-03-19 09:24:12 +01003738 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003739 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003740
3741 if (audio_device_is_digital(device)) {
3742 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003743 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003744 }
Eric Laurente552edb2014-03-10 17:42:56 -07003745
Eric Laurent3b73df72014-03-11 09:06:29 -07003746 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003747 // first list already open outputs that can be routed to this device
3748 for (size_t i = 0; i < mOutputs.size(); i++) {
3749 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003750 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003751 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003752 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3753 outputs.add(mOutputs.keyAt(i));
3754 } else {
3755 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003756 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003757 }
Eric Laurente552edb2014-03-10 17:42:56 -07003758 }
3759 }
3760 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003761 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003762 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003763 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
3764 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003765 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003766 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003767 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003768 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08003769 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
3770 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08003771 }
Eric Laurente552edb2014-03-10 17:42:56 -07003772 }
3773 }
3774 }
3775
Eric Laurent7b279bb2015-12-14 10:18:23 -08003776 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003777
Eric Laurente552edb2014-03-10 17:42:56 -07003778 if (profiles.isEmpty() && outputs.isEmpty()) {
3779 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3780 return BAD_VALUE;
3781 }
3782
3783 // open outputs for matching profiles if needed. Direct outputs are also opened to
3784 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3785 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003786 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003787
3788 // nothing to do if one output is already opened for this profile
3789 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003790 for (j = 0; j < outputs.size(); j++) {
3791 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003792 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003793 // matching profile: save the sample rates, format and channel masks supported
3794 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003795 if (audio_device_is_digital(device)) {
3796 devDesc->importAudioPort(profile);
3797 }
Eric Laurente552edb2014-03-10 17:42:56 -07003798 break;
3799 }
3800 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003801 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003802 continue;
3803 }
3804
Eric Laurent83efe1c2017-07-09 16:51:08 -07003805 ALOGV("opening output for device %08x with params %s profile %p name %s",
3806 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003807 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003809 status_t status = desc->open(nullptr, device, address,
3810 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07003811
Eric Laurentfe231122017-11-17 17:48:06 -08003812 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07003813 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003814 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003815 char *param = audio_device_address_to_parameter(device, address);
3816 mpClientInterface->setParameters(output, String8(param));
3817 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003818 }
Phil Burk00eeb322016-03-31 12:41:00 -07003819 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003820 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003821 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08003822 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003823 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003824 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08003825 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08003826 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003827 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3828 profile->pickAudioProfile(
3829 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003830 config.offload_info.sample_rate = config.sample_rate;
3831 config.offload_info.channel_mask = config.channel_mask;
3832 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08003833
3834 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
3835 AUDIO_OUTPUT_FLAG_NONE, &output);
3836 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003837 output = AUDIO_IO_HANDLE_NONE;
3838 }
Eric Laurentd4692962014-05-05 18:13:44 -07003839 }
3840
Eric Laurentcf2c0212014-07-25 16:20:43 -07003841 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003842 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003843 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003844 sp<AudioPolicyMix> policyMix;
3845 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003846 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3847 address.string());
3848 }
François Gaffie036e1e92015-03-19 10:16:24 +01003849 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003850 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003851
Eric Laurent87ffa392015-05-22 10:32:38 -07003852 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3853 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003854 // no duplicated output for direct outputs and
3855 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003856 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003857
Eric Laurentd4692962014-05-05 18:13:44 -07003858 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003859 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003860
Eric Laurentd4692962014-05-05 18:13:44 -07003861 //TODO: configure audio effect output stage here
3862
3863 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003864 duplicatedOutput =
3865 mpClientInterface->openDuplicateOutput(output,
3866 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003867 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003868 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003869 sp<SwAudioOutputDescriptor> dupOutputDesc =
3870 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3871 dupOutputDesc->mOutput1 = mPrimaryOutput;
3872 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003873 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3874 dupOutputDesc->mFormat = desc->mFormat;
3875 dupOutputDesc->mChannelMask = desc->mChannelMask;
3876 dupOutputDesc->mLatency = desc->mLatency;
3877 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003878 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003879 } else {
3880 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003881 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08003882 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01003883 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003884 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003885 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003886 }
Eric Laurente552edb2014-03-10 17:42:56 -07003887 }
3888 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003889 } else {
3890 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003891 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003892 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003893 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003894 profiles.removeAt(profile_index);
3895 profile_index--;
3896 } else {
3897 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003898 // Load digital format info only for digital devices
3899 if (audio_device_is_digital(device)) {
3900 devDesc->importAudioPort(profile);
3901 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003902
François Gaffie53615e22015-03-19 09:24:12 +01003903 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003904 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3905 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003906 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003907 NULL/*patch handle*/, address.string());
3908 }
Eric Laurente552edb2014-03-10 17:42:56 -07003909 ALOGV("checkOutputsForDevice(): adding output %d", output);
3910 }
3911 }
3912
3913 if (profiles.isEmpty()) {
3914 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3915 return BAD_VALUE;
3916 }
Eric Laurentd4692962014-05-05 18:13:44 -07003917 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003918 // check if one opened output is not needed any more after disconnecting one device
3919 for (size_t i = 0; i < mOutputs.size(); i++) {
3920 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003921 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003922 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003923 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003924 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003925 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003926 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003927 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3928 mOutputs.keyAt(i));
3929 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003930 }
Eric Laurente552edb2014-03-10 17:42:56 -07003931 }
3932 }
Eric Laurentd4692962014-05-05 18:13:44 -07003933 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003934 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003935 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
3936 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003937 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003938 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 "clearing direct output profile %zu on module %s",
3940 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01003941 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003942 }
3943 }
3944 }
3945 }
3946 return NO_ERROR;
3947}
3948
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003949status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003950 audio_policy_dev_state_t state,
3951 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003952 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003953{
Paul McLean9080a4c2015-06-18 08:24:02 -07003954 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003955 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003956
3957 if (audio_device_is_digital(device)) {
3958 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003959 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003960 }
3961
Eric Laurentd4692962014-05-05 18:13:44 -07003962 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3963 // first list already open inputs that can be routed to this device
3964 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3965 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003966 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003967 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3968 inputs.add(mInputs.keyAt(input_index));
3969 }
3970 }
3971
3972 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003973 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003974 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07003975 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003976 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08003977 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003978 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08003979
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003980 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003981 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003982 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003983 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08003984 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
3985 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08003986 }
Eric Laurentd4692962014-05-05 18:13:44 -07003987 }
3988 }
3989 }
3990
3991 if (profiles.isEmpty() && inputs.isEmpty()) {
3992 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3993 return BAD_VALUE;
3994 }
3995
3996 // open inputs for matching profiles if needed. Direct inputs are also opened to
3997 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3998 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3999
Eric Laurent1c333e22014-05-20 10:48:17 -07004000 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004001 // nothing to do if one input is already opened for this profile
4002 size_t input_index;
4003 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4004 desc = mInputs.valueAt(input_index);
4005 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004006 if (audio_device_is_digital(device)) {
4007 devDesc->importAudioPort(profile);
4008 }
Eric Laurentd4692962014-05-05 18:13:44 -07004009 break;
4010 }
4011 }
4012 if (input_index != mInputs.size()) {
4013 continue;
4014 }
4015
Eric Laurentfe231122017-11-17 17:48:06 -08004016 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004017 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004018 status_t status = desc->open(nullptr,
4019 device,
4020 address,
4021 AUDIO_SOURCE_MIC,
4022 AUDIO_INPUT_FLAG_NONE,
4023 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004024
Eric Laurentcf2c0212014-07-25 16:20:43 -07004025 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004026 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004027 char *param = audio_device_address_to_parameter(device, address);
4028 mpClientInterface->setParameters(input, String8(param));
4029 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004030 }
Phil Burk00eeb322016-03-31 12:41:00 -07004031 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004032 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004033 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004034 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004035 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004036 }
4037
4038 if (input != 0) {
4039 addInput(input, desc);
4040 }
4041 } // endif input != 0
4042
Eric Laurentcf2c0212014-07-25 16:20:43 -07004043 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004044 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004045 profiles.removeAt(profile_index);
4046 profile_index--;
4047 } else {
4048 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004049 if (audio_device_is_digital(device)) {
4050 devDesc->importAudioPort(profile);
4051 }
Eric Laurentd4692962014-05-05 18:13:44 -07004052 ALOGV("checkInputsForDevice(): adding input %d", input);
4053 }
4054 } // end scan profiles
4055
4056 if (profiles.isEmpty()) {
4057 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4058 return BAD_VALUE;
4059 }
4060 } else {
4061 // Disconnect
4062 // check if one opened input is not needed any more after disconnecting one device
4063 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4064 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004065 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004066 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4067 mInputs.keyAt(input_index));
4068 inputs.add(mInputs.keyAt(input_index));
4069 }
4070 }
4071 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004072 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004073 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004074 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004075 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004076 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004077 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004078 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4079 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004080 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004081 }
4082 }
4083 }
4084 } // end disconnect
4085
4086 return NO_ERROR;
4087}
4088
4089
Eric Laurente0720872014-03-11 09:30:41 -07004090void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004091{
4092 ALOGV("closeOutput(%d)", output);
4093
Eric Laurentc75307b2015-03-17 15:29:32 -07004094 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004095 if (outputDesc == NULL) {
4096 ALOGW("closeOutput() unknown output %d", output);
4097 return;
4098 }
François Gaffie036e1e92015-03-19 10:16:24 +01004099 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004100
Eric Laurente552edb2014-03-10 17:42:56 -07004101 // look for duplicated outputs connected to the output being removed.
4102 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004103 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004104 if (dupOutputDesc->isDuplicated() &&
4105 (dupOutputDesc->mOutput1 == outputDesc ||
4106 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004107 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004108 if (dupOutputDesc->mOutput1 == outputDesc) {
4109 outputDesc2 = dupOutputDesc->mOutput2;
4110 } else {
4111 outputDesc2 = dupOutputDesc->mOutput1;
4112 }
4113 // As all active tracks on duplicated output will be deleted,
4114 // and as they were also referenced on the other output, the reference
4115 // count for their stream type must be adjusted accordingly on
4116 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004117 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004118 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004119 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4122 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4123
4124 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004125 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004126 }
4127 }
4128
Eric Laurent05b90f82014-08-27 15:32:29 -07004129 nextAudioPortGeneration();
4130
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004131 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004132 if (index >= 0) {
4133 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004134 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004135 mAudioPatches.removeItemsAt(index);
4136 mpClientInterface->onAudioPatchListUpdate();
4137 }
4138
Eric Laurentfe231122017-11-17 17:48:06 -08004139 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004140
François Gaffie53615e22015-03-19 09:24:12 +01004141 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004142 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004143}
4144
4145void AudioPolicyManager::closeInput(audio_io_handle_t input)
4146{
4147 ALOGV("closeInput(%d)", input);
4148
4149 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4150 if (inputDesc == NULL) {
4151 ALOGW("closeInput() unknown input %d", input);
4152 return;
4153 }
4154
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004156
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004157 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004158 if (index >= 0) {
4159 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004160 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004161 mAudioPatches.removeItemsAt(index);
4162 mpClientInterface->onAudioPatchListUpdate();
4163 }
4164
Eric Laurentfe231122017-11-17 17:48:06 -08004165 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004166 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004167}
4168
Eric Laurentc75307b2015-03-17 15:29:32 -07004169SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4170 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004171 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004172{
4173 SortedVector<audio_io_handle_t> outputs;
4174
4175 ALOGVV("getOutputsForDevice() device %04x", device);
4176 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004177 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004178 i, openOutputs.valueAt(i)->isDuplicated(),
4179 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004180 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4181 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4182 outputs.add(openOutputs.keyAt(i));
4183 }
4184 }
4185 return outputs;
4186}
4187
Eric Laurente0720872014-03-11 09:30:41 -07004188bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004189 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004190{
4191 if (outputs1.size() != outputs2.size()) {
4192 return false;
4193 }
4194 for (size_t i = 0; i < outputs1.size(); i++) {
4195 if (outputs1[i] != outputs2[i]) {
4196 return false;
4197 }
4198 }
4199 return true;
4200}
4201
Eric Laurente0720872014-03-11 09:30:41 -07004202void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004203{
4204 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4205 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4206 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4207 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4208
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004209 // also take into account external policy-related changes: add all outputs which are
4210 // associated with policies in the "before" and "after" output vectors
4211 ALOGVV("checkOutputForStrategy(): policy related outputs");
4212 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004213 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004214 if (desc != 0 && desc->mPolicyMix != NULL) {
4215 srcOutputs.add(desc->mIoHandle);
4216 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4217 }
4218 }
4219 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004220 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004221 if (desc != 0 && desc->mPolicyMix != NULL) {
4222 dstOutputs.add(desc->mIoHandle);
4223 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4224 }
4225 }
4226
Eric Laurente552edb2014-03-10 17:42:56 -07004227 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4228 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4229 strategy, srcOutputs[0], dstOutputs[0]);
4230 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004231 for (audio_io_handle_t srcOut : srcOutputs) {
4232 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOut);
François Gaffiead3183e2015-03-18 16:55:35 +01004233 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004234 setStrategyMute(strategy, true, desc);
4235 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004236 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004237 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004238 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004239 if (source != 0){
4240 connectAudioSource(source);
4241 }
Eric Laurente552edb2014-03-10 17:42:56 -07004242 }
4243
4244 // Move effects associated to this strategy from previous output to new output
4245 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004246 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004247 }
4248 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004249 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004250 if (getStrategy((audio_stream_type_t)i) == strategy) {
4251 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004252 }
4253 }
4254 }
4255}
4256
Eric Laurente0720872014-03-11 09:30:41 -07004257void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004258{
François Gaffie2110e042015-03-24 08:41:51 +01004259 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004260 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004261 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004262 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004263 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004264 checkOutputForStrategy(STRATEGY_SONIFICATION);
4265 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004266 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004267 checkOutputForStrategy(STRATEGY_MEDIA);
4268 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004269 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004270}
4271
Eric Laurente0720872014-03-11 09:30:41 -07004272void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004273{
François Gaffie53615e22015-03-19 09:24:12 +01004274 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004275 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004276 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004277 return;
4278 }
4279
Eric Laurent3a4311c2014-03-17 12:00:47 -07004280 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004281 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4282 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4283 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004284
4285 // if suspended, restore A2DP output if:
4286 // ((SCO device is NOT connected) ||
4287 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4288 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004289 //
Eric Laurentf732e072016-08-03 19:30:28 -07004290 // if not suspended, suspend A2DP output if:
4291 // (SCO device is connected) &&
4292 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4293 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004294 //
4295 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004296 if (!isScoConnected ||
4297 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4298 AUDIO_POLICY_FORCE_BT_SCO) &&
4299 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4300 AUDIO_POLICY_FORCE_BT_SCO) &&
4301 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004302 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004303
4304 mpClientInterface->restoreOutput(a2dpOutput);
4305 mA2dpSuspended = false;
4306 }
4307 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004308 if (isScoConnected &&
4309 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4310 AUDIO_POLICY_FORCE_BT_SCO) ||
4311 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4312 AUDIO_POLICY_FORCE_BT_SCO) ||
4313 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004314 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004315
4316 mpClientInterface->suspendOutput(a2dpOutput);
4317 mA2dpSuspended = true;
4318 }
4319 }
4320}
4321
Eric Laurentc75307b2015-03-17 15:29:32 -07004322audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4323 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004324{
4325 audio_devices_t device = AUDIO_DEVICE_NONE;
4326
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004327 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004328 if (index >= 0) {
4329 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4330 if (patchDesc->mUid != mUidCached) {
4331 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004332 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004333 return outputDesc->device();
4334 }
4335 }
4336
Eric Laurente552edb2014-03-10 17:42:56 -07004337 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004338 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004339 // use device for strategy enforced audible
4340 // 2: we are in call or the strategy phone is active on the output:
4341 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004342 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004343 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004344 // 4: the strategy for enforced audible is active but not enforced on the output:
4345 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004346 // 5: the strategy accessibility is active on the output:
4347 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004348 // 6: the strategy "respectful" sonification is active on the output:
4349 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004350 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004351 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004352 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004353 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004354 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004355 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004356 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004357 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4359 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004360 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004361 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004362 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004363 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004364 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4365 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004366 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4367 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004368 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004369 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004370 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004371 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004372 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004373 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004374 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004375 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004376 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004377 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004378 }
4379
Eric Laurent1c333e22014-05-20 10:48:17 -07004380 ALOGV("getNewOutputDevice() selected device %x", device);
4381 return device;
4382}
4383
Eric Laurentfb66dd92016-01-28 18:32:03 -08004384audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004385{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004386 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004387
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004388 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004389 if (index >= 0) {
4390 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4391 if (patchDesc->mUid != mUidCached) {
4392 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004393 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 return inputDesc->mDevice;
4395 }
4396 }
4397
Eric Laurentfb66dd92016-01-28 18:32:03 -08004398 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4399 if (isInCall()) {
4400 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4401 } else if (source != AUDIO_SOURCE_DEFAULT) {
4402 device = getDeviceAndMixForInputSource(source);
4403 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004404
Eric Laurente552edb2014-03-10 17:42:56 -07004405 return device;
4406}
4407
Eric Laurent794fde22016-03-11 09:50:45 -08004408bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4409 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004410 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004411}
4412
Eric Laurente0720872014-03-11 09:30:41 -07004413uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004414 return (uint32_t)getStrategy(stream);
4415}
4416
Eric Laurente0720872014-03-11 09:30:41 -07004417audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004418 // By checking the range of stream before calling getStrategy, we avoid
4419 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4420 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004421 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 return AUDIO_DEVICE_NONE;
4423 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004424 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004425 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4426 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004427 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004428 }
Eric Laurent794fde22016-03-11 09:50:45 -08004429 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004430 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004431 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004432 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4433 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004434 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004435 curDevices |= outputDesc->device();
4436 }
4437 }
4438 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004439 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004440
4441 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4442 and doesn't really need to.*/
4443 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4444 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4445 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4446 }
Eric Laurente552edb2014-03-10 17:42:56 -07004447 return devices;
4448}
4449
François Gaffie2110e042015-03-24 08:41:51 +01004450routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4451{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004452 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004453 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004454}
4455
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004456uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4457 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004458 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4459 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4460 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004461 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4462 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4463 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004464 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004465 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004466}
4467
Eric Laurente0720872014-03-11 09:30:41 -07004468void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004469 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004470 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004471 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4472 updateDevicesAndOutputs();
4473 break;
4474 default:
4475 break;
4476 }
4477}
4478
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004479uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004480
4481 // skip beacon mute management if a dedicated TTS output is available
4482 if (mTtsOutputAvailable) {
4483 return 0;
4484 }
4485
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004486 switch(event) {
4487 case STARTING_OUTPUT:
4488 mBeaconMuteRefCount++;
4489 break;
4490 case STOPPING_OUTPUT:
4491 if (mBeaconMuteRefCount > 0) {
4492 mBeaconMuteRefCount--;
4493 }
4494 break;
4495 case STARTING_BEACON:
4496 mBeaconPlayingRefCount++;
4497 break;
4498 case STOPPING_BEACON:
4499 if (mBeaconPlayingRefCount > 0) {
4500 mBeaconPlayingRefCount--;
4501 }
4502 break;
4503 }
4504
4505 if (mBeaconMuteRefCount > 0) {
4506 // any playback causes beacon to be muted
4507 return setBeaconMute(true);
4508 } else {
4509 // no other playback: unmute when beacon starts playing, mute when it stops
4510 return setBeaconMute(mBeaconPlayingRefCount == 0);
4511 }
4512}
4513
4514uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4515 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4516 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4517 // keep track of muted state to avoid repeating mute/unmute operations
4518 if (mBeaconMuted != mute) {
4519 // mute/unmute AUDIO_STREAM_TTS on all outputs
4520 ALOGV("\t muting %d", mute);
4521 uint32_t maxLatency = 0;
4522 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004524 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004525 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004526 0 /*delay*/, AUDIO_DEVICE_NONE);
4527 const uint32_t latency = desc->latency() * 2;
4528 if (latency > maxLatency) {
4529 maxLatency = latency;
4530 }
4531 }
4532 mBeaconMuted = mute;
4533 return maxLatency;
4534 }
4535 return 0;
4536}
4537
Eric Laurente0720872014-03-11 09:30:41 -07004538audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004539 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004540{
Paul McLeanaa981192015-03-21 09:55:15 -07004541 // Routing
4542 // see if we have an explicit route
4543 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4544 // (getStrategy(stream)).
4545 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004546 // and activity count is non-zero and the device in the route descriptor is available
4547 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004548 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4549 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004550 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004551 if ((routeStrategy == strategy) && route->isActive() &&
4552 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004553 return route->mDeviceDescriptor->type();
4554 }
4555 }
4556
Eric Laurente552edb2014-03-10 17:42:56 -07004557 if (fromCache) {
4558 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4559 strategy, mDeviceForStrategy[strategy]);
4560 return mDeviceForStrategy[strategy];
4561 }
François Gaffie2110e042015-03-24 08:41:51 +01004562 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004563}
4564
Eric Laurente0720872014-03-11 09:30:41 -07004565void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004566{
4567 for (int i = 0; i < NUM_STRATEGIES; i++) {
4568 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4569 }
4570 mPreviousOutputs = mOutputs;
4571}
4572
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004573uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004574 audio_devices_t prevDevice,
4575 uint32_t delayMs)
4576{
4577 // mute/unmute strategies using an incompatible device combination
4578 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4579 // if unmuting, unmute only after the specified delay
4580 if (outputDesc->isDuplicated()) {
4581 return 0;
4582 }
4583
4584 uint32_t muteWaitMs = 0;
4585 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004586 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004587
4588 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4589 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004590 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004591 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4592 bool doMute = false;
4593
4594 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4595 doMute = true;
4596 outputDesc->mStrategyMutedByDevice[i] = true;
4597 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4598 doMute = true;
4599 outputDesc->mStrategyMutedByDevice[i] = false;
4600 }
Eric Laurent99401132014-05-07 19:48:15 -07004601 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004602 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004603 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004604 // skip output if it does not share any device with current output
4605 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4606 == AUDIO_DEVICE_NONE) {
4607 continue;
4608 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004609 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004610 mute ? "muting" : "unmuting", i, curDevice);
4611 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004612 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004613 if (mute) {
4614 // FIXME: should not need to double latency if volume could be applied
4615 // immediately by the audioflinger mixer. We must account for the delay
4616 // between now and the next time the audioflinger thread for this output
4617 // will process a buffer (which corresponds to one buffer size,
4618 // usually 1/2 or 1/4 of the latency).
4619 if (muteWaitMs < desc->latency() * 2) {
4620 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004621 }
4622 }
4623 }
4624 }
4625 }
4626 }
4627
Eric Laurent99401132014-05-07 19:48:15 -07004628 // temporary mute output if device selection changes to avoid volume bursts due to
4629 // different per device volumes
4630 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004631 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4632 // temporary mute duration is conservatively set to 4 times the reported latency
4633 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4634 if (muteWaitMs < tempMuteWaitMs) {
4635 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004636 }
Eric Laurentdc462862016-07-19 12:29:53 -07004637
Eric Laurent99401132014-05-07 19:48:15 -07004638 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004639 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004640 // make sure that we do not start the temporary mute period too early in case of
4641 // delayed device change
4642 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004643 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004644 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004645 }
4646 }
4647 }
4648
Eric Laurente552edb2014-03-10 17:42:56 -07004649 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4650 if (muteWaitMs > delayMs) {
4651 muteWaitMs -= delayMs;
4652 usleep(muteWaitMs * 1000);
4653 return muteWaitMs;
4654 }
4655 return 0;
4656}
4657
Eric Laurentc75307b2015-03-17 15:29:32 -07004658uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004659 audio_devices_t device,
4660 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004662 audio_patch_handle_t *patchHandle,
Andy Hung7c7124e2017-10-20 12:03:34 -07004663 const char *address,
4664 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07004665{
Eric Laurentc75307b2015-03-17 15:29:32 -07004666 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004667 AudioParameter param;
4668 uint32_t muteWaitMs;
4669
4670 if (outputDesc->isDuplicated()) {
Andy Hung7c7124e2017-10-20 12:03:34 -07004671 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
4672 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
4673 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
4674 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07004675 return muteWaitMs;
4676 }
4677 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4678 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004679 if ((device != AUDIO_DEVICE_NONE) &&
Andy Hung7c7124e2017-10-20 12:03:34 -07004680 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004681 return 0;
4682 }
4683
4684 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004685 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004686
4687 audio_devices_t prevDevice = outputDesc->mDevice;
4688
Paul McLeanaa981192015-03-21 09:55:15 -07004689 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004690
4691 if (device != AUDIO_DEVICE_NONE) {
4692 outputDesc->mDevice = device;
4693 }
Andy Hung7c7124e2017-10-20 12:03:34 -07004694
4695 // if the outputs are not materially active, there is no need to mute.
4696 if (requiresMuteCheck) {
4697 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4698 } else {
4699 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
4700 muteWaitMs = 0;
4701 }
Eric Laurente552edb2014-03-10 17:42:56 -07004702
4703 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004704 // the requested device is AUDIO_DEVICE_NONE
4705 // OR the requested device is the same as current device
4706 // AND force is not specified
4707 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004708 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004709 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4710 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004711 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004712 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004713 return muteWaitMs;
4714 }
4715
4716 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004717
Eric Laurente552edb2014-03-10 17:42:56 -07004718 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004719 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004720 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004721 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004722 DeviceVector deviceList;
4723 if ((address == NULL) || (strlen(address) == 0)) {
4724 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4725 } else {
4726 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4727 }
4728
Eric Laurent1c333e22014-05-20 10:48:17 -07004729 if (!deviceList.isEmpty()) {
4730 struct audio_patch patch;
4731 outputDesc->toAudioPortConfig(&patch.sources[0]);
4732 patch.num_sources = 1;
4733 patch.num_sinks = 0;
4734 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4735 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004736 patch.num_sinks++;
4737 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 ssize_t index;
4739 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4740 index = mAudioPatches.indexOfKey(*patchHandle);
4741 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004742 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 }
4744 sp< AudioPatch> patchDesc;
4745 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4746 if (index >= 0) {
4747 patchDesc = mAudioPatches.valueAt(index);
4748 afPatchHandle = patchDesc->mAfPatchHandle;
4749 }
4750
Eric Laurent1c333e22014-05-20 10:48:17 -07004751 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 &afPatchHandle,
4753 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004754 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4755 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004757 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004759 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 addAudioPatch(patchDesc->mHandle, patchDesc);
4761 } else {
4762 patchDesc->mPatch = patch;
4763 }
4764 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 if (patchHandle) {
4766 *patchHandle = patchDesc->mHandle;
4767 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004768 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004770 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004771 }
4772 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004773
4774 // inform all input as well
4775 for (size_t i = 0; i < mInputs.size(); i++) {
4776 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004777 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004778 AudioParameter inputCmd = AudioParameter();
4779 ALOGV("%s: inform input %d of device:%d", __func__,
4780 inputDescriptor->mIoHandle, device);
4781 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4782 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4783 inputCmd.toString(),
4784 delayMs);
4785 }
4786 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004787 }
Eric Laurente552edb2014-03-10 17:42:56 -07004788
4789 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004790 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004791
4792 return muteWaitMs;
4793}
4794
Eric Laurentc75307b2015-03-17 15:29:32 -07004795status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 int delayMs,
4797 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004798{
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 ssize_t index;
4800 if (patchHandle) {
4801 index = mAudioPatches.indexOfKey(*patchHandle);
4802 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004803 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 }
4805 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004806 return INVALID_OPERATION;
4807 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4809 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004810 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004811 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 removeAudioPatch(patchDesc->mHandle);
4813 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004814 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004815 return status;
4816}
4817
4818status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4819 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 bool force,
4821 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004822{
4823 status_t status = NO_ERROR;
4824
Eric Laurent1f2f2232014-06-02 12:01:23 -07004825 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4827 inputDesc->mDevice = device;
4828
4829 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4830 if (!deviceList.isEmpty()) {
4831 struct audio_patch patch;
4832 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004833 // AUDIO_SOURCE_HOTWORD is for internal use only:
4834 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004835 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004836 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004837 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4838 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004839 patch.num_sinks = 1;
4840 //only one input device for now
4841 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 ssize_t index;
4844 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4845 index = mAudioPatches.indexOfKey(*patchHandle);
4846 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004847 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004848 }
4849 sp< AudioPatch> patchDesc;
4850 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4851 if (index >= 0) {
4852 patchDesc = mAudioPatches.valueAt(index);
4853 afPatchHandle = patchDesc->mAfPatchHandle;
4854 }
4855
Eric Laurent1c333e22014-05-20 10:48:17 -07004856 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004858 0);
4859 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004861 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004863 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 addAudioPatch(patchDesc->mHandle, patchDesc);
4865 } else {
4866 patchDesc->mPatch = patch;
4867 }
4868 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 if (patchHandle) {
4870 *patchHandle = patchDesc->mHandle;
4871 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004872 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004874 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 }
4876 }
4877 }
4878 return status;
4879}
4880
Eric Laurent6a94d692014-05-20 11:18:06 -07004881status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4882 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004883{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004884 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 ssize_t index;
4886 if (patchHandle) {
4887 index = mAudioPatches.indexOfKey(*patchHandle);
4888 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004889 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 }
4891 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004892 return INVALID_OPERATION;
4893 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004894 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4895 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004897 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004898 removeAudioPatch(patchDesc->mHandle);
4899 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004900 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004901 return status;
4902}
4903
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004904sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004905 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004906 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004907 audio_format_t& format,
4908 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004909 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004910{
4911 // Choose an input profile based on the requested capture parameters: select the first available
4912 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004913 //
4914 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4915 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004916
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004917 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004918 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004919 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004920 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004921 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004922 format,
4923 &format /*updatedFormat*/,
4924 channelMask,
4925 &channelMask /*updatedChannelMask*/,
4926 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004927
Eric Laurente552edb2014-03-10 17:42:56 -07004928 return profile;
4929 }
4930 }
4931 }
4932 return NULL;
4933}
4934
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004935
4936audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004937 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004938{
François Gaffie036e1e92015-03-19 10:16:24 +01004939 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4940 audio_devices_t selectedDeviceFromMix =
4941 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004942
François Gaffie036e1e92015-03-19 10:16:24 +01004943 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4944 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004945 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004946 return getDeviceForInputSource(inputSource);
4947}
4948
4949audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4950{
Eric Laurentad2e7b92017-09-14 20:06:42 -07004951 // Routing
4952 // Scan the whole RouteMap to see if we have an explicit route:
4953 // if the input source in the RouteMap is the same as the argument above,
4954 // and activity count is non-zero and the device in the route descriptor is available
4955 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06004956 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4957 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004958 if ((inputSource == route->mSource) && route->isActive() &&
4959 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004960 return route->mDeviceDescriptor->type();
4961 }
4962 }
4963
4964 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004965}
4966
Eric Laurente0720872014-03-11 09:30:41 -07004967float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004968 int index,
4969 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004970{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07004971 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07004972
4973 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
4974 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
4975 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
4976 // the ringtone volume
4977 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
4978 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
4979 && isStreamActive(AUDIO_STREAM_RING, 0)) {
4980 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
4981 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
4982 }
4983
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07004984 // in-call: always cap earpiece volume by voice volume + some low headroom
4985 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
4986 switch (stream) {
4987 case AUDIO_STREAM_SYSTEM:
4988 case AUDIO_STREAM_RING:
4989 case AUDIO_STREAM_MUSIC:
4990 case AUDIO_STREAM_ALARM:
4991 case AUDIO_STREAM_NOTIFICATION:
4992 case AUDIO_STREAM_ENFORCED_AUDIBLE:
4993 case AUDIO_STREAM_DTMF:
4994 case AUDIO_STREAM_ACCESSIBILITY: {
4995 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
4996 + IN_CALL_EARPIECE_HEADROOM_DB;
4997 if (volumeDB > maxVoiceVolDb) {
4998 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
4999 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5000 volumeDB = maxVoiceVolDb;
5001 }
5002 } break;
5003 default:
5004 break;
5005 }
5006 }
5007
Eric Laurente552edb2014-03-10 17:42:56 -07005008 // if a headset is connected, apply the following rules to ring tones and notifications
5009 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005010 // - always attenuate notifications volume by 6dB
5011 // - attenuate ring tones volume by 6dB unless music is not playing and
5012 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005013 // - if music is playing, always limit the volume to current music volume,
5014 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005015 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005016 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5017 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5018 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005019 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5020 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005021 ((stream_strategy == STRATEGY_SONIFICATION)
5022 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005023 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005024 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005025 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005026 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005027 // when the phone is ringing we must consider that music could have been paused just before
5028 // by the music application and behave as if music was active if the last music track was
5029 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005030 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005031 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005032 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005033 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005034 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005035 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5036 musicDevice),
5037 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005038 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5039 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005040 if (volumeDB > minVolDB) {
5041 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005042 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005043 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005044 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5045 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5046 // on A2DP, also ensure notification volume is not too low compared to media when
5047 // intended to be played
5048 if ((volumeDB > -96.0f) &&
5049 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5050 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5051 stream, device,
5052 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5053 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5054 }
5055 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005056 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5057 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005058 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005059 }
5060 }
5061
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005062 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005063}
5064
Eric Laurente0720872014-03-11 09:30:41 -07005065status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005066 int index,
5067 const sp<AudioOutputDescriptor>& outputDesc,
5068 audio_devices_t device,
5069 int delayMs,
5070 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005071{
Eric Laurente552edb2014-03-10 17:42:56 -07005072 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005073 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005074 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005075 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005076 return NO_ERROR;
5077 }
François Gaffie2110e042015-03-24 08:41:51 +01005078 audio_policy_forced_cfg_t forceUseForComm =
5079 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005080 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005081 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5082 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005083 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005084 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005085 return INVALID_OPERATION;
5086 }
5087
Eric Laurentc75307b2015-03-17 15:29:32 -07005088 if (device == AUDIO_DEVICE_NONE) {
5089 device = outputDesc->device();
5090 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005091
Eric Laurentffbc80f2015-03-18 18:30:19 -07005092 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005093 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005094 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005095 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005096
Eric Laurentffbc80f2015-03-18 18:30:19 -07005097 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005098
Eric Laurent3b73df72014-03-11 09:06:29 -07005099 if (stream == AUDIO_STREAM_VOICE_CALL ||
5100 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005101 float voiceVolume;
5102 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005103 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005104 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005105 } else {
5106 voiceVolume = 1.0;
5107 }
5108
Eric Laurent18fba842016-03-31 14:41:26 -07005109 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005110 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5111 mLastVoiceVolume = voiceVolume;
5112 }
5113 }
5114
5115 return NO_ERROR;
5116}
5117
Eric Laurentc75307b2015-03-17 15:29:32 -07005118void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5119 audio_devices_t device,
5120 int delayMs,
5121 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005122{
Eric Laurentc75307b2015-03-17 15:29:32 -07005123 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005124
Eric Laurent794fde22016-03-11 09:50:45 -08005125 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005126 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005127 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005128 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005129 device,
5130 delayMs,
5131 force);
5132 }
5133}
5134
Eric Laurente0720872014-03-11 09:30:41 -07005135void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005136 bool on,
5137 const sp<AudioOutputDescriptor>& outputDesc,
5138 int delayMs,
5139 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005140{
Eric Laurent72249d52015-06-08 11:12:15 -07005141 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5142 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005143 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005144 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005145 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005146 }
5147 }
5148}
5149
Eric Laurente0720872014-03-11 09:30:41 -07005150void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005151 bool on,
5152 const sp<AudioOutputDescriptor>& outputDesc,
5153 int delayMs,
5154 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005155{
Eric Laurente552edb2014-03-10 17:42:56 -07005156 if (device == AUDIO_DEVICE_NONE) {
5157 device = outputDesc->device();
5158 }
5159
Eric Laurentc75307b2015-03-17 15:29:32 -07005160 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5161 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005162
5163 if (on) {
5164 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005165 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005166 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005167 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005169 }
5170 }
5171 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5172 outputDesc->mMuteCount[stream]++;
5173 } else {
5174 if (outputDesc->mMuteCount[stream] == 0) {
5175 ALOGV("setStreamMute() unmuting non muted stream!");
5176 return;
5177 }
5178 if (--outputDesc->mMuteCount[stream] == 0) {
5179 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005180 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005181 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005182 device,
5183 delayMs);
5184 }
5185 }
5186}
5187
Eric Laurente0720872014-03-11 09:30:41 -07005188void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005189 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005190{
Eric Laurent87ffa392015-05-22 10:32:38 -07005191 if(!hasPrimaryOutput()) {
5192 return;
5193 }
5194
Eric Laurente552edb2014-03-10 17:42:56 -07005195 // if the stream pertains to sonification strategy and we are in call we must
5196 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5197 // in the device used for phone strategy and play the tone if the selected device does not
5198 // interfere with the device used for phone strategy
5199 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5200 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005201 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005202 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5203 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005204 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005205 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5206 stream, starting, outputDesc->mDevice, stateChange);
5207 if (outputDesc->mRefCount[stream]) {
5208 int muteCount = 1;
5209 if (stateChange) {
5210 muteCount = outputDesc->mRefCount[stream];
5211 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005212 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005213 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5214 for (int i = 0; i < muteCount; i++) {
5215 setStreamMute(stream, starting, mPrimaryOutput);
5216 }
5217 } else {
5218 ALOGV("handleIncallSonification() high visibility");
5219 if (outputDesc->device() &
5220 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5221 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5222 for (int i = 0; i < muteCount; i++) {
5223 setStreamMute(stream, starting, mPrimaryOutput);
5224 }
5225 }
5226 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005227 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5228 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005229 } else {
5230 mpClientInterface->stopTone();
5231 }
5232 }
5233 }
5234 }
5235}
5236
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005237audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5238{
5239 // flags to stream type mapping
5240 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5241 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5242 }
5243 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5244 return AUDIO_STREAM_BLUETOOTH_SCO;
5245 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005246 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5247 return AUDIO_STREAM_TTS;
5248 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005249
5250 // usage to stream type mapping
5251 switch (attr->usage) {
5252 case AUDIO_USAGE_MEDIA:
5253 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005254 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005255 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5256 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005257 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5258 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005259 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5260 return AUDIO_STREAM_SYSTEM;
5261 case AUDIO_USAGE_VOICE_COMMUNICATION:
5262 return AUDIO_STREAM_VOICE_CALL;
5263
5264 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5265 return AUDIO_STREAM_DTMF;
5266
5267 case AUDIO_USAGE_ALARM:
5268 return AUDIO_STREAM_ALARM;
5269 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5270 return AUDIO_STREAM_RING;
5271
5272 case AUDIO_USAGE_NOTIFICATION:
5273 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5274 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5275 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5276 case AUDIO_USAGE_NOTIFICATION_EVENT:
5277 return AUDIO_STREAM_NOTIFICATION;
5278
5279 case AUDIO_USAGE_UNKNOWN:
5280 default:
5281 return AUDIO_STREAM_MUSIC;
5282 }
5283}
Eric Laurente83b55d2014-11-14 10:06:21 -08005284
François Gaffie53615e22015-03-19 09:24:12 +01005285bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5286{
Eric Laurente83b55d2014-11-14 10:06:21 -08005287 // has flags that map to a strategy?
5288 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5289 return true;
5290 }
5291
5292 // has known usage?
5293 switch (paa->usage) {
5294 case AUDIO_USAGE_UNKNOWN:
5295 case AUDIO_USAGE_MEDIA:
5296 case AUDIO_USAGE_VOICE_COMMUNICATION:
5297 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5298 case AUDIO_USAGE_ALARM:
5299 case AUDIO_USAGE_NOTIFICATION:
5300 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5301 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5302 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5303 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5304 case AUDIO_USAGE_NOTIFICATION_EVENT:
5305 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5306 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5307 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5308 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005309 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005310 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005311 break;
5312 default:
5313 return false;
5314 }
5315 return true;
5316}
5317
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005318bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005319 routing_strategy strategy, uint32_t inPastMs,
5320 nsecs_t sysTime) const
5321{
5322 if ((sysTime == 0) && (inPastMs != 0)) {
5323 sysTime = systemTime();
5324 }
Eric Laurent794fde22016-03-11 09:50:45 -08005325 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005326 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5327 (NUM_STRATEGIES == strategy)) &&
5328 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5329 return true;
5330 }
5331 }
5332 return false;
5333}
5334
François Gaffie2110e042015-03-24 08:41:51 +01005335audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5336{
5337 return mEngine->getForceUse(usage);
5338}
5339
5340bool AudioPolicyManager::isInCall()
5341{
5342 return isStateInCall(mEngine->getPhoneState());
5343}
5344
5345bool AudioPolicyManager::isStateInCall(int state)
5346{
5347 return is_state_in_call(state);
5348}
5349
Eric Laurentd60560a2015-04-10 11:31:20 -07005350void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5351{
5352 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5353 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5354 if (sourceDesc->mDevice->equals(deviceDesc)) {
5355 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5356 stopAudioSource(sourceDesc->getHandle());
5357 }
5358 }
5359
5360 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5361 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5362 bool release = false;
5363 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5364 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5365 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5366 source->ext.device.type == deviceDesc->type()) {
5367 release = true;
5368 }
5369 }
5370 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5371 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5372 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5373 sink->ext.device.type == deviceDesc->type()) {
5374 release = true;
5375 }
5376 }
5377 if (release) {
5378 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5379 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5380 }
5381 }
5382}
5383
Phil Burk09bc4612016-02-24 15:58:15 -08005384// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005385void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5386 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005387 // TODO Set this based on Config properties.
5388 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005389
5390 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5391 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005392 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005393
5394 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005395 bool supportsAC3 = false;
5396 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005397 bool supportsIEC61937 = false;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005398 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
Phil Burk09bc4612016-02-24 15:58:15 -08005399 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005400 switch (format) {
5401 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005402 supportsAC3 = true;
5403 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005404 case AUDIO_FORMAT_E_AC3:
5405 case AUDIO_FORMAT_DTS:
5406 case AUDIO_FORMAT_DTS_HD:
jiabindd601152017-11-27 14:53:37 -08005407 // If ALWAYS, remove all other surround formats here since we will add them later.
5408 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5409 formats.removeAt(formatIndex);
5410 formatIndex--;
5411 }
Phil Burk07ac1142016-03-25 13:39:29 -07005412 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005413 break;
5414 case AUDIO_FORMAT_IEC61937:
5415 supportsIEC61937 = true;
5416 break;
5417 default:
5418 break;
5419 }
5420 }
Phil Burk09bc4612016-02-24 15:58:15 -08005421
5422 // Modify formats based on surround preferences.
5423 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005424 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5425 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5426 // Remove surround sound related formats.
5427 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5428 audio_format_t format = formats[formatIndex];
5429 switch(format) {
5430 case AUDIO_FORMAT_AC3:
5431 case AUDIO_FORMAT_E_AC3:
5432 case AUDIO_FORMAT_DTS:
5433 case AUDIO_FORMAT_DTS_HD:
5434 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005435 formats.removeAt(formatIndex);
5436 break;
5437 default:
5438 formatIndex++; // keep it
5439 break;
5440 }
Phil Burk09bc4612016-02-24 15:58:15 -08005441 }
Phil Burk07ac1142016-03-25 13:39:29 -07005442 supportsAC3 = false;
5443 supportsOtherSurround = false;
5444 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005445 }
Phil Burk07ac1142016-03-25 13:39:29 -07005446 } else { // AUTO or ALWAYS
5447 // Most TVs support AC3 even if they do not report it in the EDID.
5448 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5449 && !supportsAC3) {
5450 formats.add(AUDIO_FORMAT_AC3);
5451 supportsAC3 = true;
5452 }
5453
5454 // If ALWAYS, add support for raw surround formats if all are missing.
5455 // This assumes that if any of these formats are reported by the HAL
5456 // then the report is valid and should not be modified.
jiabindd601152017-11-27 14:53:37 -08005457 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
Phil Burk07ac1142016-03-25 13:39:29 -07005458 formats.add(AUDIO_FORMAT_E_AC3);
5459 formats.add(AUDIO_FORMAT_DTS);
5460 formats.add(AUDIO_FORMAT_DTS_HD);
5461 supportsOtherSurround = true;
5462 }
5463
5464 // Add support for IEC61937 if any raw surround supported.
5465 // The HAL could do this but add it here, just in case.
5466 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5467 formats.add(AUDIO_FORMAT_IEC61937);
5468 supportsIEC61937 = true;
5469 }
Phil Burk09bc4612016-02-24 15:58:15 -08005470 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005471}
5472
5473// Modify the list of channel masks supported.
5474void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5475 ChannelsVector &channelMasks = *channelMasksPtr;
5476 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5477 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5478
5479 // If NEVER, then remove support for channelMasks > stereo.
5480 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5481 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5482 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5483 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5484 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5485 channelMasks.removeAt(maskIndex);
5486 } else {
5487 maskIndex++;
5488 }
5489 }
5490 // If ALWAYS, then make sure we at least support 5.1
5491 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5492 bool supports5dot1 = false;
5493 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005494 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005495 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5496 supports5dot1 = true;
5497 break;
5498 }
5499 }
5500 // If not then add 5.1 support.
5501 if (!supports5dot1) {
5502 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5503 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5504 }
Phil Burk09bc4612016-02-24 15:58:15 -08005505 }
5506}
5507
Phil Burk00eeb322016-03-31 12:41:00 -07005508void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5509 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005510 AudioProfileVector &profiles)
5511{
5512 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005513
François Gaffie112b0af2015-11-19 16:13:25 +01005514 // Format MUST be checked first to update the list of AudioProfile
5515 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005516 reply = mpClientInterface->getParameters(
5517 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005518 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005519 AudioParameter repliedParameters(reply);
5520 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005521 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005522 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5523 return;
5524 }
Phil Burk09bc4612016-02-24 15:58:15 -08005525 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005526 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005527 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005528 }
Phil Burk09bc4612016-02-24 15:58:15 -08005529 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005530 }
François Gaffie112b0af2015-11-19 16:13:25 +01005531
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005532 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005533 ChannelsVector channelMasks;
5534 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005535 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005536 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005537
5538 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005539 reply = mpClientInterface->getParameters(
5540 ioHandle,
5541 requestedParameters.toString() + ";" +
5542 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005543 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005544 AudioParameter repliedParameters(reply);
5545 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005546 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005547 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005548 }
5549 }
5550 if (profiles.hasDynamicChannelsFor(format)) {
5551 reply = mpClientInterface->getParameters(ioHandle,
5552 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005553 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005554 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005555 AudioParameter repliedParameters(reply);
5556 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005557 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005558 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005559 if (device == AUDIO_DEVICE_OUT_HDMI) {
5560 filterSurroundChannelMasks(&channelMasks);
5561 }
François Gaffie112b0af2015-11-19 16:13:25 +01005562 }
5563 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005564 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005565 }
5566}
Eric Laurentd60560a2015-04-10 11:31:20 -07005567
Eric Laurente552edb2014-03-10 17:42:56 -07005568}; // namespace android