blob: 19df76b7b4fd8a88282146c17a386d80743283a9 [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"
Aniket Kumar Lataadb11ed2018-01-31 20:26:59 -080029#define AUDIO_POLICY_A2DP_OFFLOAD_XML_CONFIG_FILE_NAME "audio_policy_a2dp_offload_configuration.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010030
Eric Laurentd4692962014-05-05 18:13:44 -070031#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070032#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070033
François Gaffie2110e042015-03-24 08:41:51 +010034#include <AudioPolicyManagerInterface.h>
35#include <AudioPolicyEngineInstance.h>
Mathias Agopian05d19b02017-02-28 16:28:19 -080036#include <cutils/atomic.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070041#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070042#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070043#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010045#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010046#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010048#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010050#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010051#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurent3b73df72014-03-11 09:06:29 -070053namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurentdc462862016-07-19 12:29:53 -070055//FIXME: workaround for truncated touch sounds
56// to be removed when the problem is handled by system UI
57#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070058
59// Largest difference in dB on earpiece in call between the voice volume and another
60// media / notification / system volume.
61constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
62
Eric Laurente552edb2014-03-10 17:42:56 -070063// ----------------------------------------------------------------------------
64// AudioPolicyInterface implementation
65// ----------------------------------------------------------------------------
66
Eric Laurente0720872014-03-11 09:30:41 -070067status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080068 audio_policy_dev_state_t state,
69 const char *device_address,
70 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070071{
Paul McLeane743a472015-01-28 11:07:31 -080072 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080073}
74
François Gaffie44481e72016-04-20 07:49:57 +020075void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
76 audio_policy_dev_state_t state,
77 const String8 &device_address)
78{
79 AudioParameter param(device_address);
80 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070081 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020082 param.addInt(key, device);
83 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
84}
85
Eric Laurentc73ca6e2014-12-12 14:34:22 -080086status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080087 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080088 const char *device_address,
89 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080090{
Paul McLeane743a472015-01-28 11:07:31 -080091 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
92- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070093
94 // connect/disconnect only 1 device at a time
95 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
96
François Gaffie53615e22015-03-19 09:24:12 +010097 sp<DeviceDescriptor> devDesc =
98 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080099
Eric Laurente552edb2014-03-10 17:42:56 -0700100 // handle output devices
101 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700102 SortedVector <audio_io_handle_t> outputs;
103
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
105
Eric Laurente552edb2014-03-10 17:42:56 -0700106 // save a copy of the opened output descriptors before any output is opened or closed
107 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
108 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700109 switch (state)
110 {
111 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800112 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700113 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700114 ALOGW("setDeviceConnectionState() device already connected: %x", device);
115 return INVALID_OPERATION;
116 }
117 ALOGV("setDeviceConnectionState() connecting device %x", device);
118
Eric Laurente552edb2014-03-10 17:42:56 -0700119 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 index = mAvailableOutputDevices.add(devDesc);
121 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100122 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700123 if (module == 0) {
124 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
125 device);
126 mAvailableOutputDevices.remove(devDesc);
127 return INVALID_OPERATION;
128 }
Paul McLeane743a472015-01-28 11:07:31 -0800129 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700130 } else {
131 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700132 }
133
François Gaffie44481e72016-04-20 07:49:57 +0200134 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
135 // parameters on newly connected devices (instead of opening the outputs...)
136 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
137
Eric Laurenta1d525f2015-01-29 13:36:45 -0800138 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700139 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200140
141 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
142 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700143 return INVALID_OPERATION;
144 }
François Gaffie2110e042015-03-24 08:41:51 +0100145 // Propagate device availability to Engine
146 mEngine->setDeviceConnectionState(devDesc, state);
147
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700148 // outputs should never be empty here
149 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
150 "checkOutputsForDevice() returned no outputs but status OK");
151 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
152 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800153
Eric Laurent3ae5f312015-02-03 17:12:08 -0800154 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700155 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700156 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700157 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700158 ALOGW("setDeviceConnectionState() device not connected: %x", device);
159 return INVALID_OPERATION;
160 }
161
Paul McLean5c477aa2014-08-20 16:47:57 -0700162 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
163
Paul McLeane743a472015-01-28 11:07:31 -0800164 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200165 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700166
Eric Laurente552edb2014-03-10 17:42:56 -0700167 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700168 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700169
Eric Laurenta1d525f2015-01-29 13:36:45 -0800170 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100171
172 // Propagate device availability to Engine
173 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700174 } break;
175
176 default:
177 ALOGE("setDeviceConnectionState() invalid state: %x", state);
178 return BAD_VALUE;
179 }
180
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
182 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700183 checkA2dpSuspend();
184 checkOutputForAllStrategies();
185 // outputs must be closed after checkOutputForAllStrategies() is executed
186 if (!outputs.isEmpty()) {
187 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700188 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // close unused outputs after device disconnection or direct outputs that have been
190 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700191 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700192 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
193 (desc->mDirectOpenCount == 0))) {
194 closeOutput(outputs[i]);
195 }
196 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 // check again after closing A2DP output to reset mA2dpSuspended if needed
198 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700199 }
200
201 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700202 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700203 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
204 updateCallRouting(newDevice);
205 }
Eric Laurente552edb2014-03-10 17:42:56 -0700206 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700207 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
208 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
209 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 // do not force device change on duplicated output because if device is 0, it will
211 // also force a device 0 for the two outputs it is duplicated to which may override
212 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700213 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100214 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700215 // always force when disconnecting (a non-duplicated device)
216 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700217 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700218 }
Eric Laurente552edb2014-03-10 17:42:56 -0700219 }
220
Eric Laurentd60560a2015-04-10 11:31:20 -0700221 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
222 cleanUpForDevice(devDesc);
223 }
224
Eric Laurent72aa32f2014-05-30 18:51:48 -0700225 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700226 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700227 } // end if is output device
228
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle input devices
230 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700231 SortedVector <audio_io_handle_t> inputs;
232
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700234 switch (state)
235 {
236 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700239 ALOGW("setDeviceConnectionState() device already connected: %d", device);
240 return INVALID_OPERATION;
241 }
François Gaffie53615e22015-03-19 09:24:12 +0100242 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700243 if (module == NULL) {
244 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
245 device);
246 return INVALID_OPERATION;
247 }
François Gaffie44481e72016-04-20 07:49:57 +0200248
249 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
250 // parameters on newly connected devices (instead of opening the inputs...)
251 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
252
Paul McLean9080a4c2015-06-18 08:24:02 -0700253 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200254 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
255 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700256 return INVALID_OPERATION;
257 }
258
Eric Laurent3a4311c2014-03-17 12:00:47 -0700259 index = mAvailableInputDevices.add(devDesc);
260 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800261 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 } else {
263 return NO_MEMORY;
264 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800265
François Gaffie2110e042015-03-24 08:41:51 +0100266 // Propagate device availability to Engine
267 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700268 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700269
270 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700271 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700273 ALOGW("setDeviceConnectionState() device not connected: %d", device);
274 return INVALID_OPERATION;
275 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
277 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
278
279 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200280 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700281
Paul McLean9080a4c2015-06-18 08:24:02 -0700282 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700283 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700284
François Gaffie2110e042015-03-24 08:41:51 +0100285 // Propagate device availability to Engine
286 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700287 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700288
289 default:
290 ALOGE("setDeviceConnectionState() invalid state: %x", state);
291 return BAD_VALUE;
292 }
293
Eric Laurentd4692962014-05-05 18:13:44 -0700294 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700295 // As the input device list can impact the output device selection, update
296 // getDeviceForStrategy() cache
297 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700298
Eric Laurent87ffa392015-05-22 10:32:38 -0700299 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700300 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
301 updateCallRouting(newDevice);
302 }
303
Eric Laurentd60560a2015-04-10 11:31:20 -0700304 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
305 cleanUpForDevice(devDesc);
306 }
307
Eric Laurentb52c1522014-05-20 11:27:36 -0700308 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700309 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700310 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700311
312 ALOGW("setDeviceConnectionState() invalid device: %x", device);
313 return BAD_VALUE;
314}
315
Eric Laurente0720872014-03-11 09:30:41 -0700316audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100317 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700318{
Eric Laurent634b7142016-04-20 13:48:02 -0700319 sp<DeviceDescriptor> devDesc =
320 mHwModules.getDeviceDescriptor(device, device_address, "",
321 (strlen(device_address) != 0)/*matchAddress*/);
322
323 if (devDesc == 0) {
324 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
325 device, device_address);
326 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
327 }
François Gaffie53615e22015-03-19 09:24:12 +0100328
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 DeviceVector *deviceVector;
330
Eric Laurente552edb2014-03-10 17:42:56 -0700331 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700332 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700333 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700334 deviceVector = &mAvailableInputDevices;
335 } else {
336 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
337 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700338 }
Eric Laurent634b7142016-04-20 13:48:02 -0700339
340 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
341 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800342}
343
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800344status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
345 const char *device_address,
346 const char *device_name)
347{
348 status_t status;
349
350 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
351 device, device_address, device_name);
352
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800353 // connect/disconnect only 1 device at a time
354 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
355
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800356 // Check if the device is currently connected
357 sp<DeviceDescriptor> devDesc =
358 mHwModules.getDeviceDescriptor(device, device_address, device_name);
359 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
360 if (index < 0) {
361 // Nothing to do: device is not connected
362 return NO_ERROR;
363 }
364
365 // Toggle the device state: UNAVAILABLE -> AVAILABLE
366 // This will force reading again the device configuration
367 status = setDeviceConnectionState(device,
368 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
369 device_address, device_name);
370 if (status != NO_ERROR) {
371 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
372 status);
373 return status;
374 }
375
376 status = setDeviceConnectionState(device,
377 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
378 device_address, device_name);
379 if (status != NO_ERROR) {
380 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
381 status);
382 return status;
383 }
384
385 return NO_ERROR;
386}
387
Eric Laurentdc462862016-07-19 12:29:53 -0700388uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700389{
390 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700391 status_t status;
392 audio_patch_handle_t afPatchHandle;
393 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700394 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700395
Andy Hunga76c7de2016-12-13 19:14:31 -0800396 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700397 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700398 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800399 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700400 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
401
402 // release existing RX patch if any
403 if (mCallRxPatch != 0) {
404 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
405 mCallRxPatch.clear();
406 }
407 // release TX patch if any
408 if (mCallTxPatch != 0) {
409 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
410 mCallTxPatch.clear();
411 }
412
413 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
414 // via setOutputDevice() on primary output.
415 // Otherwise, create two audio patches for TX and RX path.
416 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700417 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700418 // If the TX device is also on the primary HW module, setOutputDevice() will take care
419 // of it due to legacy implementation. If not, create a patch.
420 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
421 == AUDIO_DEVICE_NONE) {
422 createTxPatch = true;
423 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700424 } else { // create RX path audio patch
425 struct audio_patch patch;
426
427 patch.num_sources = 1;
428 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
430 ALOG_ASSERT(!deviceList.isEmpty(),
431 "updateCallRouting() selected device not in output device list");
432 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
433 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
434 ALOG_ASSERT(!deviceList.isEmpty(),
435 "updateCallRouting() no telephony RX device");
436 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
437
438 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
439 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
440
441 // request to reuse existing output stream if one is already opened to reach the RX device
442 SortedVector<audio_io_handle_t> outputs =
443 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700444 audio_io_handle_t output = selectOutput(outputs,
445 AUDIO_OUTPUT_FLAG_NONE,
446 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700447 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700448 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449 ALOG_ASSERT(!outputDesc->isDuplicated(),
450 "updateCallRouting() RX device output is duplicated");
451 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700452 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453 patch.num_sources = 2;
454 }
455
456 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700457 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700458 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
459 status);
460 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100461 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 mCallRxPatch->mAfPatchHandle = afPatchHandle;
463 mCallRxPatch->mUid = mUidCached;
464 }
465 createTxPatch = true;
466 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700467 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700469
Eric Laurentc2730ba2014-07-20 15:47:07 -0700470 patch.num_sources = 1;
471 patch.num_sinks = 1;
472 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
473 ALOG_ASSERT(!deviceList.isEmpty(),
474 "updateCallRouting() selected device not in input device list");
475 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
476 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
477 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
478 ALOG_ASSERT(!deviceList.isEmpty(),
479 "updateCallRouting() no telephony TX device");
480 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
481 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
482
483 SortedVector<audio_io_handle_t> outputs =
484 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700485 audio_io_handle_t output = selectOutput(outputs,
486 AUDIO_OUTPUT_FLAG_NONE,
487 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700488 // request to reuse existing output stream if one is already opened to reach the TX
489 // path output device
490 if (output != AUDIO_IO_HANDLE_NONE) {
491 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
492 ALOG_ASSERT(!outputDesc->isDuplicated(),
493 "updateCallRouting() RX device output is duplicated");
494 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700495 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700496 patch.num_sources = 2;
497 }
498
Eric Laurentc0a889f2015-10-14 14:36:34 -0700499 // terminate active capture if on the same HW module as the call TX source device
500 // FIXME: would be better to refine to only inputs whose profile connects to the
501 // call TX device but this information is not in the audio patch and logic here must be
502 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800503 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
504 for (size_t i = 0; i < activeInputs.size(); i++) {
505 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
506 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
507 AudioSessionCollection activeSessions =
508 activeDesc->getAudioSessions(true /*activeOnly*/);
509 for (size_t j = 0; j < activeSessions.size(); j++) {
510 audio_session_t activeSession = activeSessions.keyAt(j);
511 stopInput(activeDesc->mIoHandle, activeSession);
512 releaseInput(activeDesc->mIoHandle, activeSession);
513 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700514 }
515 }
516
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700518 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
520 status);
521 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100522 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523 mCallTxPatch->mAfPatchHandle = afPatchHandle;
524 mCallTxPatch->mUid = mUidCached;
525 }
526 }
Eric Laurentdc462862016-07-19 12:29:53 -0700527
528 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700529}
530
Eric Laurente0720872014-03-11 09:30:41 -0700531void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700532{
533 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100534 // store previous phone state for management of sonification strategy below
535 int oldState = mEngine->getPhoneState();
536
537 if (mEngine->setPhoneState(state) != NO_ERROR) {
538 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700539 return;
540 }
François Gaffie2110e042015-03-24 08:41:51 +0100541 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700542 // if leaving call state, handle special case of active streams
543 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700544 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700545 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800546 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700547 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700548 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800549
Eric Laurent63dea1d2015-07-02 17:10:28 -0700550 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800551 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700552 }
553
François Gaffie2110e042015-03-24 08:41:51 +0100554 /**
555 * Switching to or from incall state or switching between telephony and VoIP lead to force
556 * routing command.
557 */
558 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
559 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700560
561 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700562 checkA2dpSuspend();
563 checkOutputForAllStrategies();
564 updateDevicesAndOutputs();
565
Eric Laurente552edb2014-03-10 17:42:56 -0700566 int delayMs = 0;
567 if (isStateInCall(state)) {
568 nsecs_t sysTime = systemTime();
569 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700571 // mute media and sonification strategies and delay device switch by the largest
572 // latency of any output where either strategy is active.
573 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100574 if ((isStrategyActive(desc, STRATEGY_MEDIA,
575 SONIFICATION_HEADSET_MUSIC_DELAY,
576 sysTime) ||
577 isStrategyActive(desc, STRATEGY_SONIFICATION,
578 SONIFICATION_HEADSET_MUSIC_DELAY,
579 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700580 (delayMs < (int)desc->latency()*2)) {
581 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700582 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700583 setStrategyMute(STRATEGY_MEDIA, true, desc);
584 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700585 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700586 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
587 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700588 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
589 }
590 }
591
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 if (hasPrimaryOutput()) {
593 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
594 // the device returned is not necessarily reachable via this output
595 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
596 // force routing command to audio hardware when ending call
597 // even if no device change is needed
598 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
599 rxDevice = mPrimaryOutput->device();
600 }
Eric Laurente552edb2014-03-10 17:42:56 -0700601
Eric Laurent87ffa392015-05-22 10:32:38 -0700602 if (state == AUDIO_MODE_IN_CALL) {
603 updateCallRouting(rxDevice, delayMs);
604 } else if (oldState == AUDIO_MODE_IN_CALL) {
605 if (mCallRxPatch != 0) {
606 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
607 mCallRxPatch.clear();
608 }
609 if (mCallTxPatch != 0) {
610 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
611 mCallTxPatch.clear();
612 }
613 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
614 } else {
615 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700616 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617 }
Eric Laurente552edb2014-03-10 17:42:56 -0700618 // if entering in call state, handle special case of active streams
619 // pertaining to sonification strategy see handleIncallSonification()
620 if (isStateInCall(state)) {
621 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800622 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700624 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700625
626 // force reevaluating accessibility routing when call starts
627 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700628 }
629
630 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700631 if (state == AUDIO_MODE_RINGTONE &&
632 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700633 mLimitRingtoneVolume = true;
634 } else {
635 mLimitRingtoneVolume = false;
636 }
637}
638
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700639audio_mode_t AudioPolicyManager::getPhoneState() {
640 return mEngine->getPhoneState();
641}
642
Eric Laurente0720872014-03-11 09:30:41 -0700643void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700645{
François Gaffie2110e042015-03-24 08:41:51 +0100646 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700647 if (config == mEngine->getForceUse(usage)) {
648 return;
649 }
Eric Laurente552edb2014-03-10 17:42:56 -0700650
François Gaffie2110e042015-03-24 08:41:51 +0100651 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
652 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
653 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700654 }
François Gaffie2110e042015-03-24 08:41:51 +0100655 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
656 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
657 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700658
659 // check for device and output changes triggered by new force usage
660 checkA2dpSuspend();
661 checkOutputForAllStrategies();
662 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800663
Eric Laurentdc462862016-07-19 12:29:53 -0700664 //FIXME: workaround for truncated touch sounds
665 // to be removed when the problem is handled by system UI
666 uint32_t delayMs = 0;
667 uint32_t waitMs = 0;
668 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
669 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
670 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700671 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700673 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674 }
Eric Laurente552edb2014-03-10 17:42:56 -0700675 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700676 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
677 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
678 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700679 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
680 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681 }
Eric Laurente552edb2014-03-10 17:42:56 -0700682 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700683 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700684 }
685 }
686
Eric Laurentfb66dd92016-01-28 18:32:03 -0800687 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
688 for (size_t i = 0; i < activeInputs.size(); i++) {
689 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
690 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700691 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 if (activeDesc->mProfile->getSupportedDevices().types() &
693 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
694 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700695 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800696 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700697 }
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
Eric Laurente552edb2014-03-10 17:42:56 -0700699}
700
Eric Laurente0720872014-03-11 09:30:41 -0700701void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700702{
703 ALOGV("setSystemProperty() property %s, value %s", property, value);
704}
705
706// Find a direct output profile compatible with the parameters passed, even if the input flags do
707// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800708sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700709 audio_devices_t device,
710 uint32_t samplingRate,
711 audio_format_t format,
712 audio_channel_mask_t channelMask,
713 audio_output_flags_t flags)
714{
Eric Laurent861a6282015-05-18 15:40:16 -0700715 // only retain flags that will drive the direct output profile selection
716 // if explicitly requested
717 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700718 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
719 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700720 flags =
721 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
722
723 sp<IOProfile> profile;
724
Eric Laurente552edb2014-03-10 17:42:56 -0700725 for (size_t i = 0; i < mHwModules.size(); i++) {
726 if (mHwModules[i]->mHandle == 0) {
727 continue;
728 }
729 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
731 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700732 samplingRate, NULL /*updatedSamplingRate*/,
733 format, NULL /*updatedFormat*/,
734 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700735 flags)) {
736 continue;
737 }
738 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100739 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700740 continue;
741 }
742 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100743 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700744 continue;
745 }
746 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700749 }
Eric Laurente552edb2014-03-10 17:42:56 -0700750 }
751 }
Eric Laurent861a6282015-05-18 15:40:16 -0700752 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700753}
754
Eric Laurente0720872014-03-11 09:30:41 -0700755audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100756 uint32_t samplingRate,
757 audio_format_t format,
758 audio_channel_mask_t channelMask,
759 audio_output_flags_t flags,
760 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700761{
Eric Laurent3b73df72014-03-11 09:06:29 -0700762 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
764 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
765 device, stream, samplingRate, format, channelMask, flags);
766
Kevin Rocard169753c2017-03-06 14:18:23 -0800767 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
768 channelMask, flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769}
770
Eric Laurente83b55d2014-11-14 10:06:21 -0800771status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
772 audio_io_handle_t *output,
773 audio_session_t session,
774 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700775 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800776 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800777 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700778 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800779 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780{
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 audio_attributes_t attributes;
782 if (attr != NULL) {
783 if (!isValidAttributes(attr)) {
784 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
785 attr->usage, attr->content_type, attr->flags,
786 attr->tags);
787 return BAD_VALUE;
788 }
789 attributes = *attr;
790 } else {
791 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
792 ALOGE("getOutputForAttr(): invalid stream type");
793 return BAD_VALUE;
794 }
795 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800797
798 // TODO: check for existing client for this port ID
799 if (*portId == AUDIO_PORT_HANDLE_NONE) {
800 *portId = AudioPort::getNextUniqueId();
801 }
802
Eric Laurentc75307b2015-03-17 15:29:32 -0700803 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800804 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100805 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800806 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100807 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800808 }
François Gaffie036e1e92015-03-19 10:16:24 +0100809 *stream = streamTypefromAttributesInt(&attributes);
810 *output = desc->mIoHandle;
811 ALOGV("getOutputForAttr() returns output %d", *output);
812 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800813 }
814 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
815 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
816 return BAD_VALUE;
817 }
818
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
820 " session %d selectedDeviceId %d",
821 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700823
824 *stream = streamTypefromAttributesInt(&attributes);
825
826 // Explicit routing?
827 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700828 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
829 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
830 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
831 deviceDesc = mAvailableOutputDevices[i];
832 break;
833 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700834 }
835 }
836 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700837
Eric Laurente83b55d2014-11-14 10:06:21 -0800838 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700839 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700840
Eric Laurente83b55d2014-11-14 10:06:21 -0800841 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700842 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
843 }
844
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700845 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800846 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700847
Kevin Rocard169753c2017-03-06 14:18:23 -0800848 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800849 config->sample_rate, config->format, config->channel_mask,
850 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800851 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700852 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800853 return INVALID_OPERATION;
854 }
Paul McLeanaa981192015-03-21 09:55:15 -0700855
Eric Laurent2ac76942017-06-22 17:17:09 -0700856 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
857 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
858 : AUDIO_PORT_HANDLE_NONE;
859
860 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863}
864
865audio_io_handle_t AudioPolicyManager::getOutputForDevice(
866 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800867 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700868 audio_stream_type_t stream,
869 uint32_t samplingRate,
870 audio_format_t format,
871 audio_channel_mask_t channelMask,
872 audio_output_flags_t flags,
873 const audio_offload_info_t *offloadInfo)
874{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700875 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700876 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878#ifdef AUDIO_POLICY_TEST
879 if (mCurOutput != 0) {
880 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
881 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
882
883 if (mTestOutputs[mCurOutput] == 0) {
884 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700885 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
886 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700887 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700888 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700889 outputDesc->mFlags =
890 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700892 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
893 config.sample_rate = mTestSamplingRate;
894 config.channel_mask = mTestChannels;
895 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700896 if (offloadInfo != NULL) {
897 config.offload_info = *offloadInfo;
898 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700899 status = mpClientInterface->openOutput(0,
900 &mTestOutputs[mCurOutput],
901 &config,
902 &outputDesc->mDevice,
903 String8(""),
904 &outputDesc->mLatency,
905 outputDesc->mFlags);
906 if (status == NO_ERROR) {
907 outputDesc->mSamplingRate = config.sample_rate;
908 outputDesc->mFormat = config.format;
909 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700910 AudioParameter outputCmd = AudioParameter();
911 outputCmd.addInt(String8("set_id"),mCurOutput);
912 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
913 addOutput(mTestOutputs[mCurOutput], outputDesc);
914 }
915 }
916 return mTestOutputs[mCurOutput];
917 }
918#endif //AUDIO_POLICY_TEST
919
920 // open a direct output if required by specified parameters
921 //force direct flag if offload flag is set: offloading implies a direct output stream
922 // and all common behaviors are driven by checking only the direct flag
923 // this should normally be set appropriately in the policy configuration file
924 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700925 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700926 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700927 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
928 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
929 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800930 // only allow deep buffering for music stream type
931 if (stream != AUDIO_STREAM_MUSIC) {
932 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700933 } else if (/* stream == AUDIO_STREAM_MUSIC && */
934 flags == AUDIO_OUTPUT_FLAG_NONE &&
935 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
936 // use DEEP_BUFFER as default output for music stream type
937 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800938 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700939 if (stream == AUDIO_STREAM_TTS) {
940 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700941 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700942 audio_is_linear_pcm(format)) {
943 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
944 AUDIO_OUTPUT_FLAG_DIRECT);
945 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700946 }
Eric Laurente552edb2014-03-10 17:42:56 -0700947
Eric Laurentb732cf52014-09-24 19:08:21 -0700948 sp<IOProfile> profile;
949
950 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700951 // and not explicitly requested
952 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800953 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700954 audio_channel_count_from_out_mask(channelMask) <= 2) {
955 goto non_direct_output;
956 }
957
Andy Hung2ddee192015-12-18 17:34:44 -0800958 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
959 // This prevents creating an offloaded track and tearing it down immediately after start
960 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700961 // FIXME: We should check the audio session here but we do not have it in this context.
962 // This may prevent offloading in rare situations where effects are left active by apps
963 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700964
Eric Laurente552edb2014-03-10 17:42:56 -0700965 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800966 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700967 profile = getProfileForDirectOutput(device,
968 samplingRate,
969 format,
970 channelMask,
971 (audio_output_flags_t)flags);
972 }
973
Eric Laurent1c333e22014-05-20 10:48:17 -0700974 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700975 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700976
977 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700978 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700979 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
980 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800981 // reuse direct output if currently open by the same client
982 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700983 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800984 audio_formats_match(format, outputDesc->mFormat) &&
985 (channelMask == outputDesc->mChannelMask)) {
Kevin Rocard169753c2017-03-06 14:18:23 -0800986 if (session == outputDesc->mDirectClientSession) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800987 outputDesc->mDirectOpenCount++;
Kevin Rocard169753c2017-03-06 14:18:23 -0800988 ALOGV("getOutput() reusing direct output %d for session %d",
989 mOutputs.keyAt(i), session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800990 return mOutputs.keyAt(i);
991 } else {
Kevin Rocard169753c2017-03-06 14:18:23 -0800992 ALOGV("getOutput() do not reuse direct output because current client (%d) "
993 "is not the same as requesting client (%d)",
994 outputDesc->mDirectClientSession, session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800995 goto non_direct_output;
996 }
Eric Laurente552edb2014-03-10 17:42:56 -0700997 }
998 }
999 }
1000 // close direct output if currently open and configured with different parameters
1001 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001002 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001003 }
Eric Laurent861a6282015-05-18 15:40:16 -07001004
1005 // if the selected profile is offloaded and no offload info was specified,
1006 // create a default one
1007 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001008 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -07001009 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1010 defaultOffloadInfo.sample_rate = samplingRate;
1011 defaultOffloadInfo.channel_mask = channelMask;
1012 defaultOffloadInfo.format = format;
1013 defaultOffloadInfo.stream_type = stream;
1014 defaultOffloadInfo.bit_rate = 0;
1015 defaultOffloadInfo.duration_us = -1;
1016 defaultOffloadInfo.has_video = true; // conservative
1017 defaultOffloadInfo.is_streaming = true; // likely
1018 offloadInfo = &defaultOffloadInfo;
1019 }
1020
Eric Laurentc75307b2015-03-17 15:29:32 -07001021 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07001022 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001023 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001024 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001025 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1026 config.sample_rate = samplingRate;
1027 config.channel_mask = channelMask;
1028 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001029 if (offloadInfo != NULL) {
1030 config.offload_info = *offloadInfo;
1031 }
Eric Laurente3014102017-05-03 11:15:43 -07001032 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1033 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1034 : String8("");
Eric Laurent322b4d22015-04-03 15:57:54 -07001035 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001036 &output,
1037 &config,
1038 &outputDesc->mDevice,
Eric Laurente3014102017-05-03 11:15:43 -07001039 address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001040 &outputDesc->mLatency,
1041 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001042
1043 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001044 if (status != NO_ERROR ||
1045 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001046 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001047 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001048 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1049 "format %d %d, channelMask %04x %04x", output, samplingRate,
1050 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1051 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001052 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001053 mpClientInterface->closeOutput(output);
1054 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001055 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001056 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001057 goto non_direct_output;
1058 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001059 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001060 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001061 outputDesc->mSamplingRate = config.sample_rate;
1062 outputDesc->mChannelMask = config.channel_mask;
1063 outputDesc->mFormat = config.format;
1064 outputDesc->mRefCount[stream] = 0;
1065 outputDesc->mStopTime[stream] = 0;
1066 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001067 outputDesc->mDirectClientSession = session;
1068
Eric Laurente552edb2014-03-10 17:42:56 -07001069 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001070 mPreviousOutputs = mOutputs;
1071 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001072 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001073 return output;
1074 }
1075
Eric Laurentb732cf52014-09-24 19:08:21 -07001076non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001077
1078 // A request for HW A/V sync cannot fallback to a mixed output because time
1079 // stamps are embedded in audio data
1080 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1081 return AUDIO_IO_HANDLE_NONE;
1082 }
1083
Eric Laurente552edb2014-03-10 17:42:56 -07001084 // ignoring channel mask due to downmix capability in mixer
1085
1086 // open a non direct output
1087
1088 // for non direct outputs, only PCM is supported
1089 if (audio_is_linear_pcm(format)) {
1090 // get which output is suitable for the specified stream. The actual
1091 // routing change will happen when startOutput() will be called
1092 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1093
Eric Laurent8838a382014-09-08 16:44:28 -07001094 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1095 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1096 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001097 }
1098 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1099 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1100
Eric Laurente552edb2014-03-10 17:42:56 -07001101 return output;
1102}
1103
Eric Laurente0720872014-03-11 09:30:41 -07001104audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001105 audio_output_flags_t flags,
1106 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001107{
1108 // select one output among several that provide a path to a particular device or set of
1109 // devices (the list was previously build by getOutputsForDevice()).
1110 // The priority is as follows:
1111 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001112 // 2: the output with the bit depth the closest to the requested one
1113 // 3: the primary output
1114 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001115
1116 if (outputs.size() == 0) {
1117 return 0;
1118 }
1119 if (outputs.size() == 1) {
1120 return outputs[0];
1121 }
1122
1123 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001124 audio_io_handle_t outputForFlags = 0;
1125 audio_io_handle_t outputForPrimary = 0;
1126 audio_io_handle_t outputForFormat = 0;
1127 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1128 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001129
1130 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001131 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001132 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001133 // if a valid format is specified, skip output if not compatible
1134 if (format != AUDIO_FORMAT_INVALID) {
1135 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001136 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001137 continue;
1138 }
1139 } else if (!audio_is_linear_pcm(format)) {
1140 continue;
1141 }
Eric Laurente6930022016-02-11 10:20:40 -08001142 if (AudioPort::isBetterFormatMatch(
1143 outputDesc->mFormat, bestFormat, format)) {
1144 outputForFormat = outputs[i];
1145 bestFormat = outputDesc->mFormat;
1146 }
Eric Laurent8838a382014-09-08 16:44:28 -07001147 }
1148
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001149 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001150 if (commonFlags >= maxCommonFlags) {
1151 if (commonFlags == maxCommonFlags) {
1152 if (AudioPort::isBetterFormatMatch(
1153 outputDesc->mFormat, bestFormatForFlags, format)) {
1154 outputForFlags = outputs[i];
1155 bestFormatForFlags = outputDesc->mFormat;
1156 }
1157 } else {
1158 outputForFlags = outputs[i];
1159 maxCommonFlags = commonFlags;
1160 bestFormatForFlags = outputDesc->mFormat;
1161 }
Eric Laurente552edb2014-03-10 17:42:56 -07001162 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1163 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001164 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001165 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001166 }
1167 }
1168 }
1169
Eric Laurente6930022016-02-11 10:20:40 -08001170 if (outputForFlags != 0) {
1171 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
Eric Laurente6930022016-02-11 10:20:40 -08001173 if (outputForFormat != 0) {
1174 return outputForFormat;
1175 }
1176 if (outputForPrimary != 0) {
1177 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001178 }
1179
1180 return outputs[0];
1181}
1182
Eric Laurente0720872014-03-11 09:30:41 -07001183status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001184 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001185 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
Paul McLeanaa981192015-03-21 09:55:15 -07001187 ALOGV("startOutput() output %d, stream %d, session %d",
1188 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001189 ssize_t index = mOutputs.indexOfKey(output);
1190 if (index < 0) {
1191 ALOGW("startOutput() unknown output %d", output);
1192 return BAD_VALUE;
1193 }
1194
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1196
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001197 // Routing?
1198 mOutputRoutes.incRouteActivity(session);
1199
Eric Laurentc75307b2015-03-17 15:29:32 -07001200 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001201 AudioMix *policyMix = NULL;
1202 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001203 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001204 policyMix = outputDesc->mPolicyMix;
1205 address = policyMix->mDeviceAddress.string();
1206 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1207 newDevice = policyMix->mDeviceType;
1208 } else {
1209 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1210 }
Eric Laurent493404d2015-04-21 15:07:36 -07001211 } else if (mOutputRoutes.hasRouteChanged(session)) {
1212 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001213 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001214 } else {
1215 newDevice = AUDIO_DEVICE_NONE;
1216 }
1217
1218 uint32_t delayMs = 0;
1219
Eric Laurentc40d9692016-04-13 19:14:13 -07001220 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001221
1222 if (status != NO_ERROR) {
1223 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001224 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001225 }
1226 // Automatically enable the remote submix input when output is started on a re routing mix
1227 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001228 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1229 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001230 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1231 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001232 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001233 "remote-submix");
1234 }
1235
1236 if (delayMs != 0) {
1237 usleep(delayMs * 1000);
1238 }
1239
1240 return status;
1241}
1242
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001243status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001244 audio_stream_type_t stream,
1245 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001246 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001247 uint32_t *delayMs)
1248{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001249 // cannot start playback of STREAM_TTS if any other output is being used
1250 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001251
1252 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001253 if (stream == AUDIO_STREAM_TTS) {
1254 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001255 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001256 return INVALID_OPERATION;
1257 } else {
1258 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1259 }
1260 } else {
1261 // some playback other than beacon starts
1262 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1263 }
1264
Eric Laurent77305a62016-07-25 16:39:22 -07001265 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001266 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001267 bool force = !outputDesc->isActive() &&
1268 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001269
Eric Laurente552edb2014-03-10 17:42:56 -07001270 // increment usage count for this stream on the requested output:
1271 // NOTE that the usage count is the same for duplicated output and hardware output which is
1272 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1273 outputDesc->changeRefCount(stream, 1);
1274
Eric Laurent36829f92017-04-07 19:04:42 -07001275 if (stream == AUDIO_STREAM_MUSIC) {
1276 selectOutputForMusicEffects();
1277 }
1278
Eric Laurent493404d2015-04-21 15:07:36 -07001279 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001280 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001281 if (device == AUDIO_DEVICE_NONE) {
1282 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001283 }
Eric Laurent36829f92017-04-07 19:04:42 -07001284
Eric Laurente552edb2014-03-10 17:42:56 -07001285 routing_strategy strategy = getStrategy(stream);
1286 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001287 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1288 (beaconMuteLatency > 0);
1289 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001290 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001291 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001292 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001293 // force a device change if any other output is:
1294 // - managed by the same hw module
1295 // - has a current device selection that differs from selected device.
1296 // - supports currently selected device
1297 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001298 // In this case, the audio HAL must receive the new device selection so that it can
1299 // change the device currently selected by the other active output.
1300 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001301 desc->device() != device &&
1302 desc->supportedDevices() & device &&
1303 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001304 force = true;
1305 }
1306 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001307 // a notification so that audio focus effect can propagate, or that a mute/unmute
1308 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001309 uint32_t latency = desc->latency();
1310 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1311 waitMs = latency;
1312 }
1313 }
1314 }
Eric Laurentdc462862016-07-19 12:29:53 -07001315 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001316
1317 // handle special case for sonification while in call
1318 if (isInCall()) {
1319 handleIncallSonification(stream, true, false);
1320 }
1321
1322 // apply volume rules for current stream and device if necessary
1323 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001324 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001326 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001327
1328 // update the outputs if starting an output with a stream that can affect notification
1329 // routing
1330 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001331
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001332 // force reevaluating accessibility routing when ringtone or alarm starts
1333 if (strategy == STRATEGY_SONIFICATION) {
1334 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1335 }
Eric Laurentdc462862016-07-19 12:29:53 -07001336
1337 if (waitMs > muteWaitMs) {
1338 *delayMs = waitMs - muteWaitMs;
1339 }
Eric Laurente552edb2014-03-10 17:42:56 -07001340 }
Eric Laurentdc462862016-07-19 12:29:53 -07001341
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001342 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1343 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1344 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1345 }
1346
Eric Laurente552edb2014-03-10 17:42:56 -07001347 return NO_ERROR;
1348}
1349
1350
Eric Laurente0720872014-03-11 09:30:41 -07001351status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001352 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001353 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001354{
1355 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1356 ssize_t index = mOutputs.indexOfKey(output);
1357 if (index < 0) {
1358 ALOGW("stopOutput() unknown output %d", output);
1359 return BAD_VALUE;
1360 }
1361
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001363
Eric Laurentc75307b2015-03-17 15:29:32 -07001364 if (outputDesc->mRefCount[stream] == 1) {
1365 // Automatically disable the remote submix input when output is stopped on a
1366 // re routing mix of type MIX_TYPE_RECORDERS
1367 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1368 outputDesc->mPolicyMix != NULL &&
1369 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1370 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1371 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001372 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 "remote-submix");
1374 }
1375 }
1376
1377 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001378 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001380 int activityCount = mOutputRoutes.decRouteActivity(session);
1381 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1382
1383 if (forceDeviceUpdate) {
1384 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1385 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 }
1387
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001388 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001389}
1390
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001391status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001392 audio_stream_type_t stream,
1393 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001394{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001395 // always handle stream stop, check which stream type is stopping
1396 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1397
Eric Laurente552edb2014-03-10 17:42:56 -07001398 // handle special case for sonification while in call
1399 if (isInCall()) {
1400 handleIncallSonification(stream, false, false);
1401 }
1402
1403 if (outputDesc->mRefCount[stream] > 0) {
1404 // decrement usage count of this stream on the output
1405 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001406
Eric Laurente552edb2014-03-10 17:42:56 -07001407 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001408 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001409 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001411 // delay the device switch by twice the latency because stopOutput() is executed when
1412 // the track stop() command is received and at that time the audio track buffer can
1413 // still contain data that needs to be drained. The latency only covers the audio HAL
1414 // and kernel buffers. Also the latency does not always include additional delay in the
1415 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001416 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001417
1418 // force restoring the device selection on other active outputs if it differs from the
1419 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001420 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001421 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001424 desc->isActive() &&
1425 outputDesc->sharesHwModuleWith(desc) &&
1426 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001427 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1428 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001429 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001430 newDevice2,
1431 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001432 delayMs);
1433 // re-apply device specific volume if not done by setOutputDevice()
1434 if (!force) {
1435 applyStreamVolumes(desc, newDevice2, delayMs);
1436 }
Eric Laurente552edb2014-03-10 17:42:56 -07001437 }
1438 }
1439 // update the outputs if stopping one with a stream that can affect notification routing
1440 handleNotificationRoutingForStream(stream);
1441 }
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001442
1443 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1444 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1445 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1446 }
1447
Eric Laurent36829f92017-04-07 19:04:42 -07001448 if (stream == AUDIO_STREAM_MUSIC) {
1449 selectOutputForMusicEffects();
1450 }
Eric Laurente552edb2014-03-10 17:42:56 -07001451 return NO_ERROR;
1452 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001453 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001454 return INVALID_OPERATION;
1455 }
1456}
1457
Eric Laurente83b55d2014-11-14 10:06:21 -08001458void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001459 audio_stream_type_t stream __unused,
1460 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001461{
1462 ALOGV("releaseOutput() %d", output);
1463 ssize_t index = mOutputs.indexOfKey(output);
1464 if (index < 0) {
1465 ALOGW("releaseOutput() releasing unknown output %d", output);
1466 return;
1467 }
1468
1469#ifdef AUDIO_POLICY_TEST
1470 int testIndex = testOutputIndex(output);
1471 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001472 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001473 if (outputDesc->isActive()) {
1474 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001475 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 mTestOutputs[testIndex] = 0;
1477 }
1478 return;
1479 }
1480#endif //AUDIO_POLICY_TEST
1481
Paul McLeanaa981192015-03-21 09:55:15 -07001482 // Routing
1483 mOutputRoutes.removeRoute(session);
1484
Eric Laurentc75307b2015-03-17 15:29:32 -07001485 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001486 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001487 if (desc->mDirectOpenCount <= 0) {
1488 ALOGW("releaseOutput() invalid open count %d for output %d",
1489 desc->mDirectOpenCount, output);
1490 return;
1491 }
1492 if (--desc->mDirectOpenCount == 0) {
1493 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001494 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001495 }
1496 }
1497}
1498
1499
Eric Laurentcaf7f482014-11-25 17:50:47 -08001500status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1501 audio_io_handle_t *input,
1502 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001503 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001504 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001505 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001506 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001507 input_type_t *inputType,
1508 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001509{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001510 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1511 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001512 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001513
Eric Laurentad2e7b92017-09-14 20:06:42 -07001514 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001515 // handle legacy remote submix case where the address was not always specified
1516 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001517 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001518 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001519 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001520 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001521
Paul McLean466dc8e2015-04-17 13:15:36 -06001522 // Explicit routing?
1523 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001524 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1525 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1526 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1527 deviceDesc = mAvailableInputDevices[i];
1528 break;
1529 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001530 }
1531 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001532 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001533
Eric Laurentad2e7b92017-09-14 20:06:42 -07001534 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1535 // possible
1536 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1537 *input != AUDIO_IO_HANDLE_NONE) {
1538 ssize_t index = mInputs.indexOfKey(*input);
1539 if (index < 0) {
1540 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1541 status = BAD_VALUE;
1542 goto error;
1543 }
1544 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1545 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1546 if (audioSession == 0) {
1547 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1548 status = BAD_VALUE;
1549 goto error;
1550 }
1551 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1552 // The second call is for the first active client and sets the UID. Any further call
1553 // corresponds to a new client and is only permitted from the same UId.
1554 if (audioSession->openCount() == 1) {
1555 audioSession->setUid(uid);
1556 } else if (audioSession->uid() != uid) {
1557 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1558 uid, session, audioSession->uid());
1559 status = INVALID_OPERATION;
1560 goto error;
1561 }
1562 audioSession->changeOpenCount(1);
1563 *inputType = API_INPUT_LEGACY;
1564 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1565 *portId = AudioPort::getNextUniqueId();
1566 }
1567 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1568 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1569 : AUDIO_PORT_HANDLE_NONE;
1570 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1571
1572 return NO_ERROR;
1573 }
1574
1575 *input = AUDIO_IO_HANDLE_NONE;
1576 *inputType = API_INPUT_INVALID;
1577
1578 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1579 inputSource = AUDIO_SOURCE_MIC;
1580 }
1581 halInputSource = inputSource;
1582
1583 // TODO: check for existing client for this port ID
1584 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1585 *portId = AudioPort::getNextUniqueId();
1586 }
1587
1588 audio_devices_t device;
1589
Eric Laurentc447ded2015-01-06 08:47:05 -08001590 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001591 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001592 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1593 if (status != NO_ERROR) {
1594 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001595 }
1596 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001597 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1598 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001599 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001600 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001601 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001602 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001603 status = BAD_VALUE;
1604 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001605 }
Eric Laurentc722f302014-12-10 11:21:49 -08001606 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001607 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001608 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1609 // there is an external policy, but this input is attached to a mix of recorders,
1610 // meaning it receives audio injected into the framework, so the recorder doesn't
1611 // know about it and is therefore considered "legacy"
1612 *inputType = API_INPUT_LEGACY;
1613 } else {
1614 // recording a mix of players defined by an external policy, we're rerouting for
1615 // an external policy
1616 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1617 }
Eric Laurentc722f302014-12-10 11:21:49 -08001618 } else if (audio_is_remote_submix_device(device)) {
1619 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001620 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001621 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1622 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001623 } else {
1624 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001625 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001626
Eric Laurent599c7582015-12-07 18:05:55 -08001627 }
1628
1629 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001630 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001631 policyMix);
1632 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001633 status = INVALID_OPERATION;
1634 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001635 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001636
Eric Laurentad2e7b92017-09-14 20:06:42 -07001637 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001638 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1639 : AUDIO_PORT_HANDLE_NONE;
1640
1641 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1642 *input, *inputType, *selectedDeviceId);
1643
Eric Laurent599c7582015-12-07 18:05:55 -08001644 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001645
1646error:
1647 mInputRoutes.removeRoute(session);
1648 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001649}
1650
1651
1652audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1653 String8 address,
1654 audio_session_t session,
1655 uid_t uid,
1656 audio_source_t inputSource,
1657 uint32_t samplingRate,
1658 audio_format_t format,
1659 audio_channel_mask_t channelMask,
1660 audio_input_flags_t flags,
1661 AudioMix *policyMix)
1662{
1663 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1664 audio_source_t halInputSource = inputSource;
1665 bool isSoundTrigger = false;
1666
1667 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1668 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1669 if (index >= 0) {
1670 input = mSoundTriggerSessions.valueFor(session);
1671 isSoundTrigger = true;
1672 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1673 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1674 } else {
1675 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001676 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001677 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001678 audio_is_linear_pcm(format)) {
1679 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001680 }
1681
Andy Hungf129b032015-04-07 13:45:50 -07001682 // find a compatible input profile (not necessarily identical in parameters)
1683 sp<IOProfile> profile;
1684 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001685 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001686 audio_format_t profileFormat = format;
1687 audio_channel_mask_t profileChannelMask = channelMask;
1688 audio_input_flags_t profileFlags = flags;
1689 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001690 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001691 profileSamplingRate, profileFormat, profileChannelMask,
1692 profileFlags);
1693 if (profile != 0) {
1694 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001695 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1696 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001697 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1698 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1699 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001700 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1701 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001702 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001703 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001704 }
Eric Laurente552edb2014-03-10 17:42:56 -07001705 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001706 // Pick input sampling rate if not specified by client
1707 if (samplingRate == 0) {
1708 samplingRate = profileSamplingRate;
1709 }
Eric Laurente552edb2014-03-10 17:42:56 -07001710
Eric Laurent322b4d22015-04-03 15:57:54 -07001711 if (profile->getModuleHandle() == 0) {
1712 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001713 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001714 }
1715
Eric Laurent599c7582015-12-07 18:05:55 -08001716 sp<AudioSession> audioSession = new AudioSession(session,
1717 inputSource,
1718 format,
1719 samplingRate,
1720 channelMask,
1721 flags,
1722 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001723 isSoundTrigger,
1724 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001725
Eric Laurent74708e72017-04-07 17:13:42 -07001726// FIXME: disable concurrent capture until UI is ready
1727#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001728 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001729 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001730 for (size_t i = 0; i < mInputs.size(); i++) {
1731 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001732 // reuse input if:
1733 // - it shares the same profile
1734 // AND
1735 // - it is not a reroute submix input
1736 // AND
1737 // - it is: not used for sound trigger
1738 // OR
1739 // used for sound trigger and all clients use the same session ID
1740 //
1741 if ((profile == desc->mProfile) &&
1742 (isSoundTrigger == desc->isSoundTrigger()) &&
1743 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001744
1745 sp<AudioSession> as = desc->getAudioSession(session);
1746 if (as != 0) {
1747 // do not allow unmatching properties on same session
1748 if (as->matches(audioSession)) {
1749 as->changeOpenCount(1);
1750 } else {
1751 ALOGW("getInputForDevice() record with different attributes"
1752 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001753 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001754 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001755 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001756 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001757 }
Eric Laurentbb948092017-01-23 18:33:30 -08001758
Eric Laurent555530a2017-02-07 18:17:24 -08001759 // Reuse the already opened input stream on this profile if:
1760 // - the new capture source is background OR
1761 // - the path requested configurations match OR
1762 // - the new source priority is less than the highest source priority on this input
1763 // If the input stream cannot be reused, close it before opening a new stream
1764 // on the same profile for the new client so that the requested path configuration
1765 // can be selected.
1766 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001767 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001768 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001769 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001770 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001771 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001772 reusedInputDesc = desc;
1773 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001774 } else {
1775 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001776 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1777 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001778 }
Eric Laurent599c7582015-12-07 18:05:55 -08001779 }
1780 }
Eric Laurent599c7582015-12-07 18:05:55 -08001781
Eric Laurent555530a2017-02-07 18:17:24 -08001782 if (reusedInputDesc != 0) {
1783 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1784 for (size_t j = 0; j < sessions.size(); j++) {
1785 audio_session_t currentSession = sessions.keyAt(j);
1786 stopInput(reusedInputDesc->mIoHandle, currentSession);
1787 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1788 }
1789 }
Eric Laurent74708e72017-04-07 17:13:42 -07001790#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001791
Eric Laurentcf2c0212014-07-25 16:20:43 -07001792 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001793 config.sample_rate = profileSamplingRate;
1794 config.channel_mask = profileChannelMask;
1795 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001796
Eric Laurente3014102017-05-03 11:15:43 -07001797 if (address == "") {
1798 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1799 // the inputs vector must be of size 1, but we don't want to crash here
1800 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1801 }
1802
Eric Laurent322b4d22015-04-03 15:57:54 -07001803 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001804 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001805 &config,
1806 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001807 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001808 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001809 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001810
1811 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001812 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001813 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001814 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001815 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001816 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1817 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001818 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001819 if (input != AUDIO_IO_HANDLE_NONE) {
1820 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001821 }
Eric Laurent599c7582015-12-07 18:05:55 -08001822 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001823 }
1824
Eric Laurent1f2f2232014-06-02 12:01:23 -07001825 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001826 inputDesc->mSamplingRate = profileSamplingRate;
1827 inputDesc->mFormat = profileFormat;
1828 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001829 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001830 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001831 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001832
Eric Laurent599c7582015-12-07 18:05:55 -08001833 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001834 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001835
Eric Laurent599c7582015-12-07 18:05:55 -08001836 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001837}
1838
Eric Laurentbb948092017-01-23 18:33:30 -08001839//static
1840bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1841{
1842 return (source == AUDIO_SOURCE_HOTWORD) ||
1843 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1844 (source == AUDIO_SOURCE_FM_TUNER);
1845}
1846
Eric Laurentfb66dd92016-01-28 18:32:03 -08001847bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1848 const sp<AudioSession>& audioSession)
1849{
1850 // Do not allow capture if an active voice call is using a software patch and
1851 // the call TX source device is on the same HW module.
1852 // FIXME: would be better to refine to only inputs whose profile connects to the
1853 // call TX device but this information is not in the audio patch
1854 if (mCallTxPatch != 0 &&
1855 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1856 return false;
1857 }
1858
1859 // starting concurrent capture is enabled if:
1860 // 1) capturing for re-routing
1861 // 2) capturing for HOTWORD source
1862 // 3) capturing for FM TUNER source
1863 // 3) All other active captures are either for re-routing or HOTWORD
1864
1865 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001866 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001867 return true;
1868 }
1869
1870 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1871 for (size_t i = 0; i < activeInputs.size(); i++) {
1872 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001873 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001874 !is_virtual_input_device(activeInput->mDevice)) {
1875 return false;
1876 }
1877 }
1878
1879 return true;
1880}
1881
Chris Thornton2b864642017-06-27 21:26:07 -07001882// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1883bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1884 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1885 bool soundTriggerSupportsConcurrentCapture = false;
1886 unsigned int numModules = 0;
1887 struct sound_trigger_module_descriptor* nModules = NULL;
1888
1889 status_t status = SoundTrigger::listModules(nModules, &numModules);
1890 if (status == NO_ERROR && numModules != 0) {
1891 nModules = (struct sound_trigger_module_descriptor*) calloc(
1892 numModules, sizeof(struct sound_trigger_module_descriptor));
1893 if (nModules == NULL) {
1894 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1895 // ram the next time this function is called.
1896 ALOGE("Failed to allocate buffer for module descriptors");
1897 return false;
1898 }
1899
1900 status = SoundTrigger::listModules(nModules, &numModules);
1901 if (status == NO_ERROR) {
1902 soundTriggerSupportsConcurrentCapture = true;
1903 for (size_t i = 0; i < numModules; ++i) {
1904 soundTriggerSupportsConcurrentCapture &=
1905 nModules[i].properties.concurrent_capture;
1906 }
1907 }
1908 free(nModules);
1909 }
1910 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1911 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1912 }
1913 return mSoundTriggerSupportsConcurrentCapture;
1914}
1915
Eric Laurentfb66dd92016-01-28 18:32:03 -08001916
Eric Laurent4dc68062014-07-28 17:26:49 -07001917status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001918 audio_session_t session,
1919 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001920{
1921 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001922 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001923 ssize_t index = mInputs.indexOfKey(input);
1924 if (index < 0) {
1925 ALOGW("startInput() unknown input %d", input);
1926 return BAD_VALUE;
1927 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001928 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001929
Eric Laurent599c7582015-12-07 18:05:55 -08001930 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1931 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001932 ALOGW("startInput() unknown session %d on input %d", session, input);
1933 return BAD_VALUE;
1934 }
1935
Eric Laurent74708e72017-04-07 17:13:42 -07001936// FIXME: disable concurrent capture until UI is ready
1937#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001938 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1939 ALOGW("startInput(%d) failed: other input already started", input);
1940 return INVALID_OPERATION;
1941 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001942
Eric Laurentfb66dd92016-01-28 18:32:03 -08001943 if (isInCall()) {
1944 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1945 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001946 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001947 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001948 }
Eric Laurent74708e72017-04-07 17:13:42 -07001949#else
1950 if (!is_virtual_input_device(inputDesc->mDevice)) {
1951 if (mCallTxPatch != 0 &&
1952 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1953 ALOGW("startInput(%d) failed: call in progress", input);
1954 return INVALID_OPERATION;
1955 }
1956
1957 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1958 for (size_t i = 0; i < activeInputs.size(); i++) {
1959 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1960
1961 if (is_virtual_input_device(activeDesc->mDevice)) {
1962 continue;
1963 }
1964
Eric Laurentcb4dae22017-07-01 19:39:32 -07001965 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1966 activeDesc->getId() == inputDesc->getId()) {
1967 continue;
1968 }
1969
Eric Laurent74708e72017-04-07 17:13:42 -07001970 audio_source_t activeSource = activeDesc->inputSource(true);
1971 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1972 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1973 if (activeDesc->hasPreemptedSession(session)) {
1974 ALOGW("startInput(%d) failed for HOTWORD: "
1975 "other input %d already started for HOTWORD",
1976 input, activeDesc->mIoHandle);
1977 return INVALID_OPERATION;
1978 }
1979 } else {
1980 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1981 input, activeDesc->mIoHandle);
1982 return INVALID_OPERATION;
1983 }
1984 } else {
1985 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1986 ALOGW("startInput(%d) failed: other input %d already started",
1987 input, activeDesc->mIoHandle);
1988 return INVALID_OPERATION;
1989 }
1990 }
1991 }
1992
Chris Thornton2b864642017-06-27 21:26:07 -07001993 // We only need to check if the sound trigger session supports concurrent capture if the
1994 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1995 // that's running.
1996 const bool allowConcurrentWithSoundTrigger =
1997 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1998
Eric Laurent74708e72017-04-07 17:13:42 -07001999 // if capture is allowed, preempt currently active HOTWORD captures
2000 for (size_t i = 0; i < activeInputs.size(); i++) {
2001 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
2002
2003 if (is_virtual_input_device(activeDesc->mDevice)) {
2004 continue;
2005 }
2006
Chris Thornton2b864642017-06-27 21:26:07 -07002007 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2008 continue;
2009 }
2010
Eric Laurent74708e72017-04-07 17:13:42 -07002011 audio_source_t activeSource = activeDesc->inputSource(true);
2012 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2013 AudioSessionCollection activeSessions =
2014 activeDesc->getAudioSessions(true /*activeOnly*/);
2015 audio_session_t activeSession = activeSessions.keyAt(0);
2016 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2017 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2018 sessions.add(activeSession);
2019 inputDesc->setPreemptedSessions(sessions);
2020 stopInput(activeHandle, activeSession);
2021 releaseInput(activeHandle, activeSession);
2022 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2023 input, activeDesc->mIoHandle);
2024 }
2025 }
2026 }
2027#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002028
Eric Laurent313d1e72016-01-29 09:56:57 -08002029 // increment activity count before calling getNewInputDevice() below as only active sessions
2030 // are considered for device selection
2031 audioSession->changeActiveCount(1);
2032
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002033 // Routing?
2034 mInputRoutes.incRouteActivity(session);
2035
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002036 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002037 // indicate active capture to sound trigger service if starting capture from a mic on
2038 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002039 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002040 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002041
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002042 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2043 // if input maps to a dynamic policy with an activity listener, notify of state change
2044 if ((inputDesc->mPolicyMix != NULL)
2045 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2046 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2047 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002048 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002049
Eric Laurentf7c50102016-09-30 15:19:43 -07002050 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2051 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002052 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002053 SoundTrigger::setCaptureState(true);
2054 }
2055
2056 // automatically enable the remote submix output when input is started if not
2057 // used by a policy mix of type MIX_TYPE_RECORDERS
2058 // For remote submix (a virtual device), we open only one input per capture request.
2059 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2060 String8 address = String8("");
2061 if (inputDesc->mPolicyMix == NULL) {
2062 address = String8("0");
2063 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2064 address = inputDesc->mPolicyMix->mDeviceAddress;
2065 }
2066 if (address != "") {
2067 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2068 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2069 address, "remote-submix");
2070 }
Eric Laurentc722f302014-12-10 11:21:49 -08002071 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002072 }
Eric Laurente552edb2014-03-10 17:42:56 -07002073 }
2074
Eric Laurent599c7582015-12-07 18:05:55 -08002075 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002076
Eric Laurente552edb2014-03-10 17:42:56 -07002077 return NO_ERROR;
2078}
2079
Eric Laurent4dc68062014-07-28 17:26:49 -07002080status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2081 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002082{
2083 ALOGV("stopInput() input %d", input);
2084 ssize_t index = mInputs.indexOfKey(input);
2085 if (index < 0) {
2086 ALOGW("stopInput() unknown input %d", input);
2087 return BAD_VALUE;
2088 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002089 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurent599c7582015-12-07 18:05:55 -08002091 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002092 if (index < 0) {
2093 ALOGW("stopInput() unknown session %d on input %d", session, input);
2094 return BAD_VALUE;
2095 }
2096
Eric Laurent599c7582015-12-07 18:05:55 -08002097 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002098 ALOGW("stopInput() input %d already stopped", input);
2099 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002100 }
2101
Eric Laurent599c7582015-12-07 18:05:55 -08002102 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002103
2104 // Routing?
2105 mInputRoutes.decRouteActivity(session);
2106
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002107 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002108
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002109 if (inputDesc->isActive()) {
2110 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2111 } else {
2112 // if input maps to a dynamic policy with an activity listener, notify of state change
2113 if ((inputDesc->mPolicyMix != NULL)
2114 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2115 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2116 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002117 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002118
2119 // automatically disable the remote submix output when input is stopped if not
2120 // used by a policy mix of type MIX_TYPE_RECORDERS
2121 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2122 String8 address = String8("");
2123 if (inputDesc->mPolicyMix == NULL) {
2124 address = String8("0");
2125 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2126 address = inputDesc->mPolicyMix->mDeviceAddress;
2127 }
2128 if (address != "") {
2129 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2130 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2131 address, "remote-submix");
2132 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002133 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002134
Eric Laurentf7c50102016-09-30 15:19:43 -07002135 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002136 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002137
Eric Laurentf7c50102016-09-30 15:19:43 -07002138 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2139 // primary HW module
2140 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2141 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2142 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002143 SoundTrigger::setCaptureState(false);
2144 }
2145 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002146 }
Eric Laurente552edb2014-03-10 17:42:56 -07002147 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002149}
2150
Eric Laurent4dc68062014-07-28 17:26:49 -07002151void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2152 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002153{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002154
Eric Laurente552edb2014-03-10 17:42:56 -07002155 ALOGV("releaseInput() %d", input);
2156 ssize_t index = mInputs.indexOfKey(input);
2157 if (index < 0) {
2158 ALOGW("releaseInput() releasing unknown input %d", input);
2159 return;
2160 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002161
2162 // Routing
2163 mInputRoutes.removeRoute(session);
2164
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002165 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2166 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002167
Eric Laurent599c7582015-12-07 18:05:55 -08002168 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002169 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002170 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2171 return;
2172 }
Eric Laurent599c7582015-12-07 18:05:55 -08002173
2174 if (audioSession->openCount() == 0) {
2175 ALOGW("releaseInput() invalid open count %d on session %d",
2176 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002177 return;
2178 }
Eric Laurent599c7582015-12-07 18:05:55 -08002179
2180 if (audioSession->changeOpenCount(-1) == 0) {
2181 inputDesc->removeAudioSession(session);
2182 }
2183
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002184 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002185 ALOGV("releaseInput() exit > 0");
2186 return;
2187 }
2188
Eric Laurent05b90f82014-08-27 15:32:29 -07002189 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002190 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002191 ALOGV("releaseInput() exit");
2192}
2193
Eric Laurentd4692962014-05-05 18:13:44 -07002194void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002195 bool patchRemoved = false;
2196
Eric Laurentd4692962014-05-05 18:13:44 -07002197 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002198 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002199 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002200 if (patch_index >= 0) {
2201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002202 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002203 mAudioPatches.removeItemsAt(patch_index);
2204 patchRemoved = true;
2205 }
Eric Laurentd4692962014-05-05 18:13:44 -07002206 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2207 }
2208 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002209 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002210 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002211
2212 if (patchRemoved) {
2213 mpClientInterface->onAudioPatchListUpdate();
2214 }
Eric Laurentd4692962014-05-05 18:13:44 -07002215}
2216
Eric Laurente0720872014-03-11 09:30:41 -07002217void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002218 int indexMin,
2219 int indexMax)
2220{
2221 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002222 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002223
2224 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002225 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2226 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002227 continue;
2228 }
2229 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002230 }
Eric Laurente552edb2014-03-10 17:42:56 -07002231}
2232
Eric Laurente0720872014-03-11 09:30:41 -07002233status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002234 int index,
2235 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002236{
2237
François Gaffied1ab2bd2015-12-02 18:20:06 +01002238 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2239 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002240 return BAD_VALUE;
2241 }
2242 if (!audio_is_output_device(device)) {
2243 return BAD_VALUE;
2244 }
2245
2246 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002247 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Eric Laurent1fd372e2016-04-06 14:23:53 -07002249 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002250 stream, device, index);
2251
Eric Laurent28d09f02016-03-08 10:43:05 -08002252 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002253 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2254 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002255 continue;
2256 }
2257 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2258 }
Eric Laurente552edb2014-03-10 17:42:56 -07002259
Eric Laurent1fd372e2016-04-06 14:23:53 -07002260 // update volume on all outputs and streams matching the following:
2261 // - The requested stream (or a stream matching for volume control) is active on the output
2262 // - The device (or devices) selected by the strategy corresponding to this stream includes
2263 // the requested device
2264 // - For non default requested device, currently selected device on the output is either the
2265 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002266 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2267 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002268 status_t status = NO_ERROR;
2269 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002270 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2271 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002272 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2273 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002274 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002275 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002276 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2277 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002278 continue;
2279 }
Eric Laurent794fde22016-03-11 09:50:45 -08002280 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002281 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2282 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002283 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2284 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002285 continue;
2286 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002287 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002288 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002289 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002290 applyVolume = (curDevice & curStreamDevice) != 0;
2291 } else {
2292 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002293 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002294 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002295
Eric Laurente76f29c2016-09-14 17:17:53 -07002296 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002297 //FIXME: workaround for truncated touch sounds
2298 // delayed volume change for system stream to be removed when the problem is
2299 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002300 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002301 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2302 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002303 if (volStatus != NO_ERROR) {
2304 status = volStatus;
2305 }
2306 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002307 }
Eric Laurente552edb2014-03-10 17:42:56 -07002308 }
2309 return status;
2310}
2311
Eric Laurente0720872014-03-11 09:30:41 -07002312status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002313 int *index,
2314 audio_devices_t device)
2315{
2316 if (index == NULL) {
2317 return BAD_VALUE;
2318 }
2319 if (!audio_is_output_device(device)) {
2320 return BAD_VALUE;
2321 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002322 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002323 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002324 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002325 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2326 }
François Gaffiedfd74092015-03-19 12:10:59 +01002327 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002328
François Gaffied1ab2bd2015-12-02 18:20:06 +01002329 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002330 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2331 return NO_ERROR;
2332}
2333
Eric Laurent36829f92017-04-07 19:04:42 -07002334audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002335{
2336 // select one output among several suitable for global effects.
2337 // The priority is as follows:
2338 // 1: An offloaded output. If the effect ends up not being offloadable,
2339 // AudioFlinger will invalidate the track and the offloaded output
2340 // will be closed causing the effect to be moved to a PCM output.
2341 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002342 // 3: The primary output
2343 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002344
Eric Laurent3b73df72014-03-11 09:06:29 -07002345 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002346 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002347 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002348
Eric Laurent36829f92017-04-07 19:04:42 -07002349 if (outputs.size() == 0) {
2350 return AUDIO_IO_HANDLE_NONE;
2351 }
Eric Laurente552edb2014-03-10 17:42:56 -07002352
Eric Laurent36829f92017-04-07 19:04:42 -07002353 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2354 bool activeOnly = true;
2355
2356 while (output == AUDIO_IO_HANDLE_NONE) {
2357 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2358 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2359 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2360
2361 for (size_t i = 0; i < outputs.size(); i++) {
2362 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2363 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2364 continue;
2365 }
2366 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2367 activeOnly, i, desc->mFlags);
2368 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2369 outputOffloaded = outputs[i];
2370 }
2371 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2372 outputDeepBuffer = outputs[i];
2373 }
2374 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2375 outputPrimary = outputs[i];
2376 }
2377 }
2378 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2379 output = outputOffloaded;
2380 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2381 output = outputDeepBuffer;
2382 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2383 output = outputPrimary;
2384 } else {
2385 output = outputs[0];
2386 }
2387 activeOnly = false;
2388 }
2389
2390 if (output != mMusicEffectOutput) {
2391 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2392 mMusicEffectOutput = output;
2393 }
2394
2395 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002396 return output;
2397}
2398
Eric Laurent36829f92017-04-07 19:04:42 -07002399audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2400{
2401 return selectOutputForMusicEffects();
2402}
2403
Eric Laurente0720872014-03-11 09:30:41 -07002404status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002405 audio_io_handle_t io,
2406 uint32_t strategy,
2407 int session,
2408 int id)
2409{
2410 ssize_t index = mOutputs.indexOfKey(io);
2411 if (index < 0) {
2412 index = mInputs.indexOfKey(io);
2413 if (index < 0) {
2414 ALOGW("registerEffect() unknown io %d", io);
2415 return INVALID_OPERATION;
2416 }
2417 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002418 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002419}
2420
Eric Laurentc75307b2015-03-17 15:29:32 -07002421bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2422{
Eric Laurent28d09f02016-03-08 10:43:05 -08002423 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002424 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2425 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002426 continue;
2427 }
2428 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2429 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002430 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002431}
2432
2433bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2434{
2435 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2436}
2437
Eric Laurente0720872014-03-11 09:30:41 -07002438bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002439{
2440 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002441 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002442 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002443 return true;
2444 }
2445 }
2446 return false;
2447}
2448
Eric Laurent275e8e92014-11-30 15:14:47 -08002449// Register a list of custom mixes with their attributes and format.
2450// When a mix is registered, corresponding input and output profiles are
2451// added to the remote submix hw module. The profile contains only the
2452// parameters (sampling rate, format...) specified by the mix.
2453// The corresponding input remote submix device is also connected.
2454//
2455// When a remote submix device is connected, the address is checked to select the
2456// appropriate profile and the corresponding input or output stream is opened.
2457//
2458// When capture starts, getInputForAttr() will:
2459// - 1 look for a mix matching the address passed in attribtutes tags if any
2460// - 2 if none found, getDeviceForInputSource() will:
2461// - 2.1 look for a mix matching the attributes source
2462// - 2.2 if none found, default to device selection by policy rules
2463// At this time, the corresponding output remote submix device is also connected
2464// and active playback use cases can be transferred to this mix if needed when reconnecting
2465// after AudioTracks are invalidated
2466//
2467// When playback starts, getOutputForAttr() will:
2468// - 1 look for a mix matching the address passed in attribtutes tags if any
2469// - 2 if none found, look for a mix matching the attributes usage
2470// - 3 if none found, default to device and output selection by policy rules.
2471
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002472status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002473{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2475 status_t res = NO_ERROR;
2476
2477 sp<HwModule> rSubmixModule;
2478 // examine each mix's route type
2479 for (size_t i = 0; i < mixes.size(); i++) {
2480 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2481 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2482 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002483 break;
2484 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2486 // Loop back through "remote submix"
2487 if (rSubmixModule == 0) {
2488 for (size_t j = 0; i < mHwModules.size(); j++) {
2489 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2490 && mHwModules[j]->mHandle != 0) {
2491 rSubmixModule = mHwModules[j];
2492 break;
2493 }
2494 }
2495 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002496
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002498
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 if (rSubmixModule == 0) {
2500 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2501 res = INVALID_OPERATION;
2502 break;
2503 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002504
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002506
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002507 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002508 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002509 res = INVALID_OPERATION;
2510 break;
2511 }
2512 audio_config_t outputConfig = mixes[i].mFormat;
2513 audio_config_t inputConfig = mixes[i].mFormat;
2514 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2515 // stereo and let audio flinger do the channel conversion if needed.
2516 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2517 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2518 rSubmixModule->addOutputProfile(address, &outputConfig,
2519 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2520 rSubmixModule->addInputProfile(address, &inputConfig,
2521 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002522
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2524 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2525 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2526 address.string(), "remote-submix");
2527 } else {
2528 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2529 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2530 address.string(), "remote-submix");
2531 }
2532 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002535 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2536 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002537
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002538 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2540 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2541 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2542 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2543 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2544 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002545 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2546 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2548 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002549 } else {
2550 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 }
2552 break;
2553 }
2554 }
2555
2556 if (res != NO_ERROR) {
2557 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002558 i, device, address.string());
2559 res = INVALID_OPERATION;
2560 break;
2561 } else if (!foundOutput) {
2562 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2563 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 res = INVALID_OPERATION;
2565 break;
2566 }
Eric Laurentc722f302014-12-10 11:21:49 -08002567 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002568 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002569 if (res != NO_ERROR) {
2570 unregisterPolicyMixes(mixes);
2571 }
2572 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002573}
2574
2575status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2576{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002577 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 status_t res = NO_ERROR;
2579 sp<HwModule> rSubmixModule;
2580 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002581 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002582 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002583
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002584 if (rSubmixModule == 0) {
2585 for (size_t j = 0; i < mHwModules.size(); j++) {
2586 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2587 && mHwModules[j]->mHandle != 0) {
2588 rSubmixModule = mHwModules[j];
2589 break;
2590 }
2591 }
2592 }
2593 if (rSubmixModule == 0) {
2594 res = INVALID_OPERATION;
2595 continue;
2596 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002597
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002598 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002599
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2601 res = INVALID_OPERATION;
2602 continue;
2603 }
2604
2605 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2606 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2607 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2608 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2609 address.string(), "remote-submix");
2610 }
2611 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2612 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2613 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2614 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2615 address.string(), "remote-submix");
2616 }
2617 rSubmixModule->removeOutputProfile(address);
2618 rSubmixModule->removeInputProfile(address);
2619
2620 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2621 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2622 res = INVALID_OPERATION;
2623 continue;
2624 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002625 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002626 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002627 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002628}
2629
Eric Laurente552edb2014-03-10 17:42:56 -07002630
Eric Laurente0720872014-03-11 09:30:41 -07002631status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002632{
2633 const size_t SIZE = 256;
2634 char buffer[SIZE];
2635 String8 result;
2636
2637 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2638 result.append(buffer);
2639
Eric Laurent87ffa392015-05-22 10:32:38 -07002640 snprintf(buffer, SIZE, " Primary Output: %d\n",
2641 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002642 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002643 std::string stateLiteral;
2644 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2645 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002646 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002647 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002648 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002649 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002650 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002651 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002652 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002653 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002654 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002655 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002656 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002657 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002658 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002659 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002660 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002661 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2662 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2663 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002664 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2665 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002666 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2667 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002668
François Gaffie2110e042015-03-24 08:41:51 +01002669 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002670
François Gaffie112b0af2015-11-19 16:13:25 +01002671 mAvailableOutputDevices.dump(fd, String8("Available output"));
2672 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002673 mHwModules.dump(fd);
2674 mOutputs.dump(fd);
2675 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002676 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002677 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002678 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002679 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002680
2681 return NO_ERROR;
2682}
2683
2684// This function checks for the parameters which can be offloaded.
2685// This can be enhanced depending on the capability of the DSP and policy
2686// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002687bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002688{
2689 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002690 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002691 offloadInfo.sample_rate, offloadInfo.channel_mask,
2692 offloadInfo.format,
2693 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2694 offloadInfo.has_video);
2695
Andy Hung2ddee192015-12-18 17:34:44 -08002696 if (mMasterMono) {
2697 return false; // no offloading if mono is set.
2698 }
2699
Eric Laurente552edb2014-03-10 17:42:56 -07002700 // Check if offload has been disabled
2701 char propValue[PROPERTY_VALUE_MAX];
2702 if (property_get("audio.offload.disable", propValue, "0")) {
2703 if (atoi(propValue) != 0) {
2704 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2705 return false;
2706 }
2707 }
2708
2709 // Check if stream type is music, then only allow offload as of now.
2710 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2711 {
2712 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2713 return false;
2714 }
2715
2716 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002717 const bool allowOffloadWithVideo =
2718 property_get_bool("audio.offload.video", false /* default_value */);
2719 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002720 ALOGV("isOffloadSupported: has_video == true, returning false");
2721 return false;
2722 }
2723
2724 //If duration is less than minimum value defined in property, return false
2725 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2726 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2727 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2728 return false;
2729 }
2730 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2731 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2732 return false;
2733 }
2734
2735 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2736 // creating an offloaded track and tearing it down immediately after start when audioflinger
2737 // detects there is an active non offloadable effect.
2738 // FIXME: We should check the audio session here but we do not have it in this context.
2739 // This may prevent offloading in rare situations where effects are left active by apps
2740 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002741 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002742 return false;
2743 }
2744
2745 // See if there is a profile to support this.
2746 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002747 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002748 offloadInfo.sample_rate,
2749 offloadInfo.format,
2750 offloadInfo.channel_mask,
2751 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002752 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2753 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002754}
2755
Eric Laurent6a94d692014-05-20 11:18:06 -07002756status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2757 audio_port_type_t type,
2758 unsigned int *num_ports,
2759 struct audio_port *ports,
2760 unsigned int *generation)
2761{
2762 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2763 generation == NULL) {
2764 return BAD_VALUE;
2765 }
2766 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2767 if (ports == NULL) {
2768 *num_ports = 0;
2769 }
2770
2771 size_t portsWritten = 0;
2772 size_t portsMax = *num_ports;
2773 *num_ports = 0;
2774 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002775 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2776 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002777 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002778 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2779 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2780 continue;
2781 }
2782 if (portsWritten < portsMax) {
2783 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2784 }
2785 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002786 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002787 }
2788 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002789 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2790 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2791 continue;
2792 }
2793 if (portsWritten < portsMax) {
2794 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2795 }
2796 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002797 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 }
2799 }
2800 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2801 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2802 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2803 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2804 }
2805 *num_ports += mInputs.size();
2806 }
2807 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002808 size_t numOutputs = 0;
2809 for (size_t i = 0; i < mOutputs.size(); i++) {
2810 if (!mOutputs[i]->isDuplicated()) {
2811 numOutputs++;
2812 if (portsWritten < portsMax) {
2813 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2814 }
2815 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 }
Eric Laurent84c70242014-06-23 08:46:27 -07002817 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 }
2819 }
2820 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002821 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 return NO_ERROR;
2823}
2824
2825status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2826{
2827 return NO_ERROR;
2828}
2829
Eric Laurent6a94d692014-05-20 11:18:06 -07002830status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2831 audio_patch_handle_t *handle,
2832 uid_t uid)
2833{
2834 ALOGV("createAudioPatch()");
2835
2836 if (handle == NULL || patch == NULL) {
2837 return BAD_VALUE;
2838 }
2839 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2840
Eric Laurent874c42872014-08-08 15:13:39 -07002841 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2842 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2843 return BAD_VALUE;
2844 }
2845 // only one source per audio patch supported for now
2846 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 return INVALID_OPERATION;
2848 }
Eric Laurent874c42872014-08-08 15:13:39 -07002849
2850 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 return INVALID_OPERATION;
2852 }
Eric Laurent874c42872014-08-08 15:13:39 -07002853 for (size_t i = 0; i < patch->num_sinks; i++) {
2854 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2855 return INVALID_OPERATION;
2856 }
2857 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002858
2859 sp<AudioPatch> patchDesc;
2860 ssize_t index = mAudioPatches.indexOfKey(*handle);
2861
Eric Laurent6a94d692014-05-20 11:18:06 -07002862 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2863 patch->sources[0].role,
2864 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002865#if LOG_NDEBUG == 0
2866 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002867 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002868 patch->sinks[i].role,
2869 patch->sinks[i].type);
2870 }
2871#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002872
2873 if (index >= 0) {
2874 patchDesc = mAudioPatches.valueAt(index);
2875 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2876 mUidCached, patchDesc->mUid, uid);
2877 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2878 return INVALID_OPERATION;
2879 }
2880 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002881 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002882 }
2883
2884 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002885 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002886 if (outputDesc == NULL) {
2887 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2888 return BAD_VALUE;
2889 }
Eric Laurent84c70242014-06-23 08:46:27 -07002890 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2891 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002892 if (patchDesc != 0) {
2893 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2894 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2895 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2896 return BAD_VALUE;
2897 }
2898 }
Eric Laurent874c42872014-08-08 15:13:39 -07002899 DeviceVector devices;
2900 for (size_t i = 0; i < patch->num_sinks; i++) {
2901 // Only support mix to devices connection
2902 // TODO add support for mix to mix connection
2903 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2904 ALOGV("createAudioPatch() source mix but sink is not a device");
2905 return INVALID_OPERATION;
2906 }
2907 sp<DeviceDescriptor> devDesc =
2908 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2909 if (devDesc == 0) {
2910 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2911 return BAD_VALUE;
2912 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002913
François Gaffie53615e22015-03-19 09:24:12 +01002914 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002915 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002916 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002917 NULL, // updatedSamplingRate
2918 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002919 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002920 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002921 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002922 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002923 ALOGV("createAudioPatch() profile not supported for device %08x",
2924 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002925 return INVALID_OPERATION;
2926 }
2927 devices.add(devDesc);
2928 }
2929 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 return INVALID_OPERATION;
2931 }
Eric Laurent874c42872014-08-08 15:13:39 -07002932
Eric Laurent6a94d692014-05-20 11:18:06 -07002933 // TODO: reconfigure output format and channels here
2934 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002935 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002936 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002937 index = mAudioPatches.indexOfKey(*handle);
2938 if (index >= 0) {
2939 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2940 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2941 }
2942 patchDesc = mAudioPatches.valueAt(index);
2943 patchDesc->mUid = uid;
2944 ALOGV("createAudioPatch() success");
2945 } else {
2946 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2947 return INVALID_OPERATION;
2948 }
2949 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2950 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2951 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002952 // only one sink supported when connecting an input device to a mix
2953 if (patch->num_sinks > 1) {
2954 return INVALID_OPERATION;
2955 }
François Gaffie53615e22015-03-19 09:24:12 +01002956 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002957 if (inputDesc == NULL) {
2958 return BAD_VALUE;
2959 }
2960 if (patchDesc != 0) {
2961 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2962 return BAD_VALUE;
2963 }
2964 }
2965 sp<DeviceDescriptor> devDesc =
2966 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2967 if (devDesc == 0) {
2968 return BAD_VALUE;
2969 }
2970
François Gaffie53615e22015-03-19 09:24:12 +01002971 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002972 devDesc->mAddress,
2973 patch->sinks[0].sample_rate,
2974 NULL, /*updatedSampleRate*/
2975 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002976 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002977 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002978 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002979 // FIXME for the parameter type,
2980 // and the NONE
2981 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002982 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002983 return INVALID_OPERATION;
2984 }
2985 // TODO: reconfigure output format and channels here
2986 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002987 devDesc->type(), inputDesc->mIoHandle);
2988 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002989 index = mAudioPatches.indexOfKey(*handle);
2990 if (index >= 0) {
2991 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2992 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2993 }
2994 patchDesc = mAudioPatches.valueAt(index);
2995 patchDesc->mUid = uid;
2996 ALOGV("createAudioPatch() success");
2997 } else {
2998 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2999 return INVALID_OPERATION;
3000 }
3001 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3002 // device to device connection
3003 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003004 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 return BAD_VALUE;
3006 }
3007 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003008 sp<DeviceDescriptor> srcDeviceDesc =
3009 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003010 if (srcDeviceDesc == 0) {
3011 return BAD_VALUE;
3012 }
Eric Laurent874c42872014-08-08 15:13:39 -07003013
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 //update source and sink with our own data as the data passed in the patch may
3015 // be incomplete.
3016 struct audio_patch newPatch = *patch;
3017 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003018
Eric Laurent874c42872014-08-08 15:13:39 -07003019 for (size_t i = 0; i < patch->num_sinks; i++) {
3020 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3021 ALOGV("createAudioPatch() source device but one sink is not a device");
3022 return INVALID_OPERATION;
3023 }
3024
3025 sp<DeviceDescriptor> sinkDeviceDesc =
3026 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3027 if (sinkDeviceDesc == 0) {
3028 return BAD_VALUE;
3029 }
3030 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3031
Eric Laurent3bcf8592015-04-03 12:13:24 -07003032 // create a software bridge in PatchPanel if:
3033 // - source and sink devices are on differnt HW modules OR
3034 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003035 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003036 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003037 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003038 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003039 return INVALID_OPERATION;
3040 }
Eric Laurent874c42872014-08-08 15:13:39 -07003041 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003042 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003043 // if the sink device is reachable via an opened output stream, request to go via
3044 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003045 audio_io_handle_t output = selectOutput(outputs,
3046 AUDIO_OUTPUT_FLAG_NONE,
3047 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003048 if (output != AUDIO_IO_HANDLE_NONE) {
3049 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3050 if (outputDesc->isDuplicated()) {
3051 return INVALID_OPERATION;
3052 }
3053 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003054 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003055 newPatch.num_sources = 2;
3056 }
Eric Laurent83b88082014-06-20 18:31:16 -07003057 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 }
3059 // TODO: check from routing capabilities in config file and other conflicting patches
3060
3061 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3062 if (index >= 0) {
3063 afPatchHandle = patchDesc->mAfPatchHandle;
3064 }
3065
3066 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3067 &afPatchHandle,
3068 0);
3069 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3070 status, afPatchHandle);
3071 if (status == NO_ERROR) {
3072 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003073 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003074 addAudioPatch(patchDesc->mHandle, patchDesc);
3075 } else {
3076 patchDesc->mPatch = newPatch;
3077 }
3078 patchDesc->mAfPatchHandle = afPatchHandle;
3079 *handle = patchDesc->mHandle;
3080 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003081 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003082 } else {
3083 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3084 status);
3085 return INVALID_OPERATION;
3086 }
3087 } else {
3088 return BAD_VALUE;
3089 }
3090 } else {
3091 return BAD_VALUE;
3092 }
3093 return NO_ERROR;
3094}
3095
3096status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3097 uid_t uid)
3098{
3099 ALOGV("releaseAudioPatch() patch %d", handle);
3100
3101 ssize_t index = mAudioPatches.indexOfKey(handle);
3102
3103 if (index < 0) {
3104 return BAD_VALUE;
3105 }
3106 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3107 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3108 mUidCached, patchDesc->mUid, uid);
3109 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3110 return INVALID_OPERATION;
3111 }
3112
3113 struct audio_patch *patch = &patchDesc->mPatch;
3114 patchDesc->mUid = mUidCached;
3115 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003116 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 if (outputDesc == NULL) {
3118 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3119 return BAD_VALUE;
3120 }
3121
Eric Laurentc75307b2015-03-17 15:29:32 -07003122 setOutputDevice(outputDesc,
3123 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 true,
3125 0,
3126 NULL);
3127 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3128 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003129 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003130 if (inputDesc == NULL) {
3131 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3132 return BAD_VALUE;
3133 }
3134 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003135 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003136 true,
3137 NULL);
3138 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003139 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3140 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3141 status, patchDesc->mAfPatchHandle);
3142 removeAudioPatch(patchDesc->mHandle);
3143 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003144 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003145 } else {
3146 return BAD_VALUE;
3147 }
3148 } else {
3149 return BAD_VALUE;
3150 }
3151 return NO_ERROR;
3152}
3153
3154status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3155 struct audio_patch *patches,
3156 unsigned int *generation)
3157{
François Gaffie53615e22015-03-19 09:24:12 +01003158 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003159 return BAD_VALUE;
3160 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003162 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003163}
3164
Eric Laurente1715a42014-05-20 11:30:42 -07003165status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003166{
Eric Laurente1715a42014-05-20 11:30:42 -07003167 ALOGV("setAudioPortConfig()");
3168
3169 if (config == NULL) {
3170 return BAD_VALUE;
3171 }
3172 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3173 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003174 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3175 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003176 }
3177
Eric Laurenta121f902014-06-03 13:32:54 -07003178 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003179 if (config->type == AUDIO_PORT_TYPE_MIX) {
3180 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003181 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003182 if (outputDesc == NULL) {
3183 return BAD_VALUE;
3184 }
Eric Laurent84c70242014-06-23 08:46:27 -07003185 ALOG_ASSERT(!outputDesc->isDuplicated(),
3186 "setAudioPortConfig() called on duplicated output %d",
3187 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003188 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003189 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003190 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003191 if (inputDesc == NULL) {
3192 return BAD_VALUE;
3193 }
Eric Laurenta121f902014-06-03 13:32:54 -07003194 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003195 } else {
3196 return BAD_VALUE;
3197 }
3198 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3199 sp<DeviceDescriptor> deviceDesc;
3200 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3201 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3202 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3203 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3204 } else {
3205 return BAD_VALUE;
3206 }
3207 if (deviceDesc == NULL) {
3208 return BAD_VALUE;
3209 }
Eric Laurenta121f902014-06-03 13:32:54 -07003210 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003211 } else {
3212 return BAD_VALUE;
3213 }
3214
Eric Laurenta121f902014-06-03 13:32:54 -07003215 struct audio_port_config backupConfig;
3216 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3217 if (status == NO_ERROR) {
3218 struct audio_port_config newConfig;
3219 audioPortConfig->toAudioPortConfig(&newConfig, config);
3220 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003221 }
Eric Laurenta121f902014-06-03 13:32:54 -07003222 if (status != NO_ERROR) {
3223 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003224 }
Eric Laurente1715a42014-05-20 11:30:42 -07003225
3226 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003227}
3228
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003229void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3230{
Eric Laurentd60560a2015-04-10 11:31:20 -07003231 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003232 clearAudioPatches(uid);
3233 clearSessionRoutes(uid);
3234}
3235
Eric Laurent6a94d692014-05-20 11:18:06 -07003236void AudioPolicyManager::clearAudioPatches(uid_t uid)
3237{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003238 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3240 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003241 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003242 }
3243 }
3244}
3245
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003246void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3247 audio_io_handle_t ouptutToSkip)
3248{
3249 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3250 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3251 for (size_t j = 0; j < mOutputs.size(); j++) {
3252 if (mOutputs.keyAt(j) == ouptutToSkip) {
3253 continue;
3254 }
3255 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3256 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3257 continue;
3258 }
3259 // If the default device for this strategy is on another output mix,
3260 // invalidate all tracks in this strategy to force re connection.
3261 // Otherwise select new device on the output mix.
3262 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003263 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003264 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3265 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3266 }
3267 }
3268 } else {
3269 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3270 setOutputDevice(outputDesc, newDevice, false);
3271 }
3272 }
3273}
3274
3275void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3276{
3277 // remove output routes associated with this uid
3278 SortedVector<routing_strategy> affectedStrategies;
3279 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3280 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3281 if (route->mUid == uid) {
3282 mOutputRoutes.removeItemsAt(i);
3283 if (route->mDeviceDescriptor != 0) {
3284 affectedStrategies.add(getStrategy(route->mStreamType));
3285 }
3286 }
3287 }
3288 // reroute outputs if necessary
3289 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3290 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3291 }
3292
3293 // remove input routes associated with this uid
3294 SortedVector<audio_source_t> affectedSources;
3295 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3296 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3297 if (route->mUid == uid) {
3298 mInputRoutes.removeItemsAt(i);
3299 if (route->mDeviceDescriptor != 0) {
3300 affectedSources.add(route->mSource);
3301 }
3302 }
3303 }
3304 // reroute inputs if necessary
3305 SortedVector<audio_io_handle_t> inputsToClose;
3306 for (size_t i = 0; i < mInputs.size(); i++) {
3307 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003308 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003309 inputsToClose.add(inputDesc->mIoHandle);
3310 }
3311 }
3312 for (size_t i = 0; i < inputsToClose.size(); i++) {
3313 closeInput(inputsToClose[i]);
3314 }
3315}
3316
Eric Laurentd60560a2015-04-10 11:31:20 -07003317void AudioPolicyManager::clearAudioSources(uid_t uid)
3318{
3319 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3320 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3321 if (sourceDesc->mUid == uid) {
3322 stopAudioSource(mAudioSources.keyAt(i));
3323 }
3324 }
3325}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003326
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003327status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3328 audio_io_handle_t *ioHandle,
3329 audio_devices_t *device)
3330{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003331 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3332 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003333 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003334
François Gaffiedf372692015-03-19 10:43:27 +01003335 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003336}
3337
Eric Laurentd60560a2015-04-10 11:31:20 -07003338status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3339 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003340 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003341 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003342{
Eric Laurentd60560a2015-04-10 11:31:20 -07003343 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3344 if (source == NULL || attributes == NULL || handle == NULL) {
3345 return BAD_VALUE;
3346 }
3347
Glenn Kasten559d4392016-03-29 13:42:57 -07003348 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003349
3350 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3351 source->type != AUDIO_PORT_TYPE_DEVICE) {
3352 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3353 return INVALID_OPERATION;
3354 }
3355
3356 sp<DeviceDescriptor> srcDeviceDesc =
3357 mAvailableInputDevices.getDevice(source->ext.device.type,
3358 String8(source->ext.device.address));
3359 if (srcDeviceDesc == 0) {
3360 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3361 return BAD_VALUE;
3362 }
3363 sp<AudioSourceDescriptor> sourceDesc =
3364 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3365
3366 struct audio_patch dummyPatch;
3367 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3368 sourceDesc->mPatchDesc = patchDesc;
3369
3370 status_t status = connectAudioSource(sourceDesc);
3371 if (status == NO_ERROR) {
3372 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3373 *handle = sourceDesc->getHandle();
3374 }
3375 return status;
3376}
3377
3378status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3379{
3380 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3381
3382 // make sure we only have one patch per source.
3383 disconnectAudioSource(sourceDesc);
3384
3385 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003386 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003387 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3388
3389 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3390 sp<DeviceDescriptor> sinkDeviceDesc =
3391 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3392
3393 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3394 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3395
3396 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3397 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003398 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003399 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3400 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3401 // create patch between src device and output device
3402 // create Hwoutput and add to mHwOutputs
3403 } else {
3404 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3405 audio_io_handle_t output =
3406 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3407 if (output == AUDIO_IO_HANDLE_NONE) {
3408 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3409 return INVALID_OPERATION;
3410 }
3411 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3412 if (outputDesc->isDuplicated()) {
3413 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3414 return INVALID_OPERATION;
3415 }
3416 // create a special patch with no sink and two sources:
3417 // - the second source indicates to PatchPanel through which output mix this patch should
3418 // be connected as well as the stream type for volume control
3419 // - the sink is defined by whatever output device is currently selected for the output
3420 // though which this patch is routed.
3421 patch->num_sinks = 0;
3422 patch->num_sources = 2;
3423 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3424 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3425 patch->sources[1].ext.mix.usecase.stream = stream;
3426 status_t status = mpClientInterface->createAudioPatch(patch,
3427 &afPatchHandle,
3428 0);
3429 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3430 status, afPatchHandle);
3431 if (status != NO_ERROR) {
3432 ALOGW("%s patch panel could not connect device patch, error %d",
3433 __FUNCTION__, status);
3434 return INVALID_OPERATION;
3435 }
3436 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003437 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003438
3439 if (status != NO_ERROR) {
3440 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3441 return status;
3442 }
3443 sourceDesc->mSwOutput = outputDesc;
3444 if (delayMs != 0) {
3445 usleep(delayMs * 1000);
3446 }
3447 }
3448
3449 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3450 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3451
3452 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003453}
3454
Glenn Kasten559d4392016-03-29 13:42:57 -07003455status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003456{
Eric Laurentd60560a2015-04-10 11:31:20 -07003457 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3458 ALOGV("%s handle %d", __FUNCTION__, handle);
3459 if (sourceDesc == 0) {
3460 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3461 return BAD_VALUE;
3462 }
3463 status_t status = disconnectAudioSource(sourceDesc);
3464
3465 mAudioSources.removeItem(handle);
3466 return status;
3467}
3468
Andy Hung2ddee192015-12-18 17:34:44 -08003469status_t AudioPolicyManager::setMasterMono(bool mono)
3470{
3471 if (mMasterMono == mono) {
3472 return NO_ERROR;
3473 }
3474 mMasterMono = mono;
3475 // if enabling mono we close all offloaded devices, which will invalidate the
3476 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3477 // for recreating the new AudioTrack as non-offloaded PCM.
3478 //
3479 // If disabling mono, we leave all tracks as is: we don't know which clients
3480 // and tracks are able to be recreated as offloaded. The next "song" should
3481 // play back offloaded.
3482 if (mMasterMono) {
3483 Vector<audio_io_handle_t> offloaded;
3484 for (size_t i = 0; i < mOutputs.size(); ++i) {
3485 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3486 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3487 offloaded.push(desc->mIoHandle);
3488 }
3489 }
3490 for (size_t i = 0; i < offloaded.size(); ++i) {
3491 closeOutput(offloaded[i]);
3492 }
3493 }
3494 // update master mono for all remaining outputs
3495 for (size_t i = 0; i < mOutputs.size(); ++i) {
3496 updateMono(mOutputs.keyAt(i));
3497 }
3498 return NO_ERROR;
3499}
3500
3501status_t AudioPolicyManager::getMasterMono(bool *mono)
3502{
3503 *mono = mMasterMono;
3504 return NO_ERROR;
3505}
3506
Eric Laurentac9cef52017-06-09 15:46:26 -07003507float AudioPolicyManager::getStreamVolumeDB(
3508 audio_stream_type_t stream, int index, audio_devices_t device)
3509{
3510 return computeVolume(stream, index, device);
3511}
3512
Eric Laurentd60560a2015-04-10 11:31:20 -07003513status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3514{
3515 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3516
3517 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3518 if (patchDesc == 0) {
3519 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3520 sourceDesc->mPatchDesc->mHandle);
3521 return BAD_VALUE;
3522 }
3523 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3524
Eric Laurent28d09f02016-03-08 10:43:05 -08003525 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003526 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3527 if (swOutputDesc != 0) {
3528 stopSource(swOutputDesc, stream, false);
3529 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3530 } else {
3531 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3532 if (hwOutputDesc != 0) {
3533 // release patch between src device and output device
3534 // close Hwoutput and remove from mHwOutputs
3535 } else {
3536 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3537 }
3538 }
3539 return NO_ERROR;
3540}
3541
3542sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3543 audio_io_handle_t output, routing_strategy strategy)
3544{
3545 sp<AudioSourceDescriptor> source;
3546 for (size_t i = 0; i < mAudioSources.size(); i++) {
3547 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3548 routing_strategy sourceStrategy =
3549 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3550 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3551 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3552 source = sourceDesc;
3553 break;
3554 }
3555 }
3556 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003557}
3558
Eric Laurente552edb2014-03-10 17:42:56 -07003559// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003560// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003561// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003562uint32_t AudioPolicyManager::nextAudioPortGeneration()
3563{
3564 return android_atomic_inc(&mAudioPortGeneration);
3565}
3566
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003567#ifdef USE_XML_AUDIO_POLICY_CONF
3568// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3569static const char *kConfigLocationList[] =
3570 {"/odm/etc", "/vendor/etc", "/system/etc"};
3571static const int kConfigLocationListSize =
3572 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3573
3574static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3575 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3576 status_t ret;
3577
3578 for (int i = 0; i < kConfigLocationListSize; i++) {
3579 PolicySerializer serializer;
Aniket Kumar Lataadb11ed2018-01-31 20:26:59 -08003580 bool use_a2dp_offload_config =
3581 property_get_bool("persist.bluetooth.a2dp_offload.enable", false);
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003582 snprintf(audioPolicyXmlConfigFile,
3583 sizeof(audioPolicyXmlConfigFile),
3584 "%s/%s",
3585 kConfigLocationList[i],
Aniket Kumar Lataadb11ed2018-01-31 20:26:59 -08003586 use_a2dp_offload_config ? AUDIO_POLICY_A2DP_OFFLOAD_XML_CONFIG_FILE_NAME :
3587 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003588 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3589 if (ret == NO_ERROR) {
3590 break;
3591 }
3592 }
3593 return ret;
3594}
3595#endif
3596
Eric Laurente0720872014-03-11 09:30:41 -07003597AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003598 :
3599#ifdef AUDIO_POLICY_TEST
3600 Thread(false),
3601#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003602 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003603 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003604 mAudioPortGeneration(1),
3605 mBeaconMuteRefCount(0),
3606 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003607 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003608 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003609 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003610 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3611 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003612{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003613 mUidCached = getuid();
3614 mpClientInterface = clientInterface;
3615
3616 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3617 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3618 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3619 bool speakerDrcEnabled = false;
3620
3621#ifdef USE_XML_AUDIO_POLICY_CONF
3622 mVolumeCurves = new VolumeCurvesCollection();
3623 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3624 mDefaultOutputDevice, speakerDrcEnabled,
3625 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003626 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003627#else
3628 mVolumeCurves = new StreamDescriptorCollection();
3629 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3630 mDefaultOutputDevice, speakerDrcEnabled);
3631 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3632 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3633#endif
3634 ALOGE("could not load audio policy configuration file, setting defaults");
3635 config.setDefault();
3636 }
3637 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3638 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3639
3640 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003641 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3642 if (!engineInstance) {
3643 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3644 return;
3645 }
3646 // Retrieve the Policy Manager Interface
3647 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3648 if (mEngine == NULL) {
3649 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3650 return;
3651 }
3652 mEngine->setObserver(this);
3653 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003654 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003655 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3656
Eric Laurent3a4311c2014-03-17 12:00:47 -07003657 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003658 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003659 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3660 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003662 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003663 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003664 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003665 continue;
3666 }
3667 // open all output streams needed to access attached devices
3668 // except for direct output streams that are only opened when they are actually
3669 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003670 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003671 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3672 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003673 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003674
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003675 if (!outProfile->hasSupportedDevices()) {
3676 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003677 continue;
3678 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003679 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003680 mTtsOutputAvailable = true;
3681 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003682
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003683 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003684 continue;
3685 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003686 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003687 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3688 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003689 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003690 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003691 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003692 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003693 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003694 if ((profileType & outputDeviceTypes) == 0) {
3695 continue;
3696 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003697 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3698 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003699 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3700 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3701 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3702 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003703
3704 outputDesc->mDevice = profileType;
3705 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3706 config.sample_rate = outputDesc->mSamplingRate;
3707 config.channel_mask = outputDesc->mChannelMask;
3708 config.format = outputDesc->mFormat;
3709 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003710 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003711 &output,
3712 &config,
3713 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003714 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003715 &outputDesc->mLatency,
3716 outputDesc->mFlags);
3717
3718 if (status != NO_ERROR) {
3719 ALOGW("Cannot open output stream for device %08x on hw module %s",
3720 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003721 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003722 } else {
3723 outputDesc->mSamplingRate = config.sample_rate;
3724 outputDesc->mChannelMask = config.channel_mask;
3725 outputDesc->mFormat = config.format;
3726
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003727 for (size_t k = 0; k < supportedDevices.size(); k++) {
3728 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003729 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003730 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3731 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003732 }
3733 }
3734 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003735 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003736 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003737 }
3738 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003739 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003740 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003741 true,
3742 0,
3743 NULL,
3744 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003745 }
Eric Laurente552edb2014-03-10 17:42:56 -07003746 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003747 // open input streams needed to access attached devices to validate
3748 // mAvailableInputDevices list
3749 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3750 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003751 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003752
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003753 if (!inProfile->hasSupportedDevices()) {
3754 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003755 continue;
3756 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003757 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003758 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003759 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3760
Eric Laurentd78f1532014-09-16 16:38:20 -07003761 if ((profileType & inputDeviceTypes) == 0) {
3762 continue;
3763 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003764 sp<AudioInputDescriptor> inputDesc =
3765 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003766
Eric Laurentd78f1532014-09-16 16:38:20 -07003767 inputDesc->mDevice = profileType;
3768
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003769 // find the address
3770 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3771 // the inputs vector must be of size 1, but we don't want to crash here
3772 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3773 : String8("");
3774 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3775 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3776
Eric Laurentd78f1532014-09-16 16:38:20 -07003777 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3778 config.sample_rate = inputDesc->mSamplingRate;
3779 config.channel_mask = inputDesc->mChannelMask;
3780 config.format = inputDesc->mFormat;
3781 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003782 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003783 &input,
3784 &config,
3785 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003786 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003787 AUDIO_SOURCE_MIC,
3788 AUDIO_INPUT_FLAG_NONE);
3789
3790 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003791 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3792 for (size_t k = 0; k < supportedDevices.size(); k++) {
3793 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003794 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003795 if (index >= 0) {
3796 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3797 if (!devDesc->isAttached()) {
3798 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003799 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003800 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003801 }
3802 }
3803 mpClientInterface->closeInput(input);
3804 } else {
3805 ALOGW("Cannot open input stream for device %08x on hw module %s",
3806 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003807 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003808 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003809 }
3810 }
3811 // make sure all attached devices have been allocated a unique ID
3812 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003813 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003814 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003815 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3816 continue;
3817 }
François Gaffie2110e042015-03-24 08:41:51 +01003818 // The device is now validated and can be appended to the available devices of the engine
3819 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3820 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003821 i++;
3822 }
3823 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003824 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003825 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003826 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3827 continue;
3828 }
François Gaffie2110e042015-03-24 08:41:51 +01003829 // The device is now validated and can be appended to the available devices of the engine
3830 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3831 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003832 i++;
3833 }
3834 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003835 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003836 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003837 }
Eric Laurente552edb2014-03-10 17:42:56 -07003838
3839 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3840
3841 updateDevicesAndOutputs();
3842
3843#ifdef AUDIO_POLICY_TEST
3844 if (mPrimaryOutput != 0) {
3845 AudioParameter outputCmd = AudioParameter();
3846 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003847 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003848
3849 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3850 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003851 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3852 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003853 mTestLatencyMs = 0;
3854 mCurOutput = 0;
3855 mDirectOutput = false;
3856 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3857 mTestOutputs[i] = 0;
3858 }
3859
3860 const size_t SIZE = 256;
3861 char buffer[SIZE];
3862 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3863 run(buffer, ANDROID_PRIORITY_AUDIO);
3864 }
3865#endif //AUDIO_POLICY_TEST
3866}
3867
Eric Laurente0720872014-03-11 09:30:41 -07003868AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003869{
3870#ifdef AUDIO_POLICY_TEST
3871 exit();
3872#endif //AUDIO_POLICY_TEST
3873 for (size_t i = 0; i < mOutputs.size(); i++) {
3874 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003875 }
3876 for (size_t i = 0; i < mInputs.size(); i++) {
3877 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003878 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003879 mAvailableOutputDevices.clear();
3880 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003881 mOutputs.clear();
3882 mInputs.clear();
3883 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003884}
3885
Eric Laurente0720872014-03-11 09:30:41 -07003886status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003887{
Eric Laurent87ffa392015-05-22 10:32:38 -07003888 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003889}
3890
3891#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003892bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003893{
3894 ALOGV("entering threadLoop()");
3895 while (!exitPending())
3896 {
3897 String8 command;
3898 int valueInt;
3899 String8 value;
3900
3901 Mutex::Autolock _l(mLock);
3902 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3903
3904 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3905 AudioParameter param = AudioParameter(command);
3906
3907 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3908 valueInt != 0) {
3909 ALOGV("Test command %s received", command.string());
3910 String8 target;
3911 if (param.get(String8("target"), target) != NO_ERROR) {
3912 target = "Manager";
3913 }
3914 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3915 param.remove(String8("test_cmd_policy_output"));
3916 mCurOutput = valueInt;
3917 }
3918 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3919 param.remove(String8("test_cmd_policy_direct"));
3920 if (value == "false") {
3921 mDirectOutput = false;
3922 } else if (value == "true") {
3923 mDirectOutput = true;
3924 }
3925 }
3926 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3927 param.remove(String8("test_cmd_policy_input"));
3928 mTestInput = valueInt;
3929 }
3930
3931 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3932 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003933 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003934 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003935 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003936 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003937 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003938 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003939 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003940 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003941 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003942 if (target == "Manager") {
3943 mTestFormat = format;
3944 } else if (mTestOutputs[mCurOutput] != 0) {
3945 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003946 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003947 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3948 }
3949 }
3950 }
3951 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3952 param.remove(String8("test_cmd_policy_channels"));
3953 int channels = 0;
3954
3955 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003956 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003957 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003958 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003959 }
3960 if (channels != 0) {
3961 if (target == "Manager") {
3962 mTestChannels = channels;
3963 } else if (mTestOutputs[mCurOutput] != 0) {
3964 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003965 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003966 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3967 }
3968 }
3969 }
3970 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3971 param.remove(String8("test_cmd_policy_sampleRate"));
3972 if (valueInt >= 0 && valueInt <= 96000) {
3973 int samplingRate = valueInt;
3974 if (target == "Manager") {
3975 mTestSamplingRate = samplingRate;
3976 } else if (mTestOutputs[mCurOutput] != 0) {
3977 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003978 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003979 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3980 }
3981 }
3982 }
3983
3984 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3985 param.remove(String8("test_cmd_policy_reopen"));
3986
Eric Laurentc75307b2015-03-17 15:29:32 -07003987 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003988
Eric Laurentc75307b2015-03-17 15:29:32 -07003989 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003990
Eric Laurentc75307b2015-03-17 15:29:32 -07003991 removeOutput(mPrimaryOutput->mIoHandle);
3992 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3993 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003994 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003995 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3996 config.sample_rate = outputDesc->mSamplingRate;
3997 config.channel_mask = outputDesc->mChannelMask;
3998 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003999 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004000 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07004001 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07004002 &config,
4003 &outputDesc->mDevice,
4004 String8(""),
4005 &outputDesc->mLatency,
4006 outputDesc->mFlags);
4007 if (status != NO_ERROR) {
4008 ALOGE("Failed to reopen hardware output stream, "
4009 "samplingRate: %d, format %d, channels %d",
4010 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07004011 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004012 outputDesc->mSamplingRate = config.sample_rate;
4013 outputDesc->mChannelMask = config.channel_mask;
4014 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07004015 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07004016 AudioParameter outputCmd = AudioParameter();
4017 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07004018 mpClientInterface->setParameters(handle, outputCmd.toString());
4019 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07004020 }
4021 }
4022
4023
4024 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
4025 }
4026 }
4027 return false;
4028}
4029
Eric Laurente0720872014-03-11 09:30:41 -07004030void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07004031{
4032 {
4033 AutoMutex _l(mLock);
4034 requestExit();
4035 mWaitWorkCV.signal();
4036 }
4037 requestExitAndWait();
4038}
4039
Eric Laurente0720872014-03-11 09:30:41 -07004040int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004041{
4042 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4043 if (output == mTestOutputs[i]) return i;
4044 }
4045 return 0;
4046}
4047#endif //AUDIO_POLICY_TEST
4048
4049// ---
4050
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004051void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
François Gaffie98cc1912015-03-18 17:52:40 +01004053 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004054 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004055 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004056 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004057 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004058}
4059
François Gaffie53615e22015-03-19 09:24:12 +01004060void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4061{
4062 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004063 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004064}
4065
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004066void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004067{
François Gaffie98cc1912015-03-18 17:52:40 +01004068 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004069 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004070 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004071}
Eric Laurente552edb2014-03-10 17:42:56 -07004072
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004073void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004074 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004075 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004076 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004077 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004078 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004079 if (devDesc != 0) {
4080 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4081 desc->mIoHandle, address.string());
4082 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004083 }
4084}
4085
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004086status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004087 audio_policy_dev_state_t state,
4088 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004089 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004090{
François Gaffie53615e22015-03-19 09:24:12 +01004091 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004092 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004093
4094 if (audio_device_is_digital(device)) {
4095 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004096 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004097 }
Eric Laurente552edb2014-03-10 17:42:56 -07004098
Eric Laurent3b73df72014-03-11 09:06:29 -07004099 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004100 // first list already open outputs that can be routed to this device
4101 for (size_t i = 0; i < mOutputs.size(); i++) {
4102 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004103 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004104 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004105 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4106 outputs.add(mOutputs.keyAt(i));
4107 } else {
4108 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004109 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004110 }
Eric Laurente552edb2014-03-10 17:42:56 -07004111 }
4112 }
4113 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004114 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004115 for (size_t i = 0; i < mHwModules.size(); i++)
4116 {
4117 if (mHwModules[i]->mHandle == 0) {
4118 continue;
4119 }
4120 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4121 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004122 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004123 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004124 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004125 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004126 profiles.add(profile);
4127 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4128 }
Eric Laurente552edb2014-03-10 17:42:56 -07004129 }
4130 }
4131 }
4132
Eric Laurent7b279bb2015-12-14 10:18:23 -08004133 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004134
Eric Laurente552edb2014-03-10 17:42:56 -07004135 if (profiles.isEmpty() && outputs.isEmpty()) {
4136 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4137 return BAD_VALUE;
4138 }
4139
4140 // open outputs for matching profiles if needed. Direct outputs are also opened to
4141 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4142 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004143 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004144
4145 // nothing to do if one output is already opened for this profile
4146 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004147 for (j = 0; j < outputs.size(); j++) {
4148 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004149 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004150 // matching profile: save the sample rates, format and channel masks supported
4151 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004152 if (audio_device_is_digital(device)) {
4153 devDesc->importAudioPort(profile);
4154 }
Eric Laurente552edb2014-03-10 17:42:56 -07004155 break;
4156 }
4157 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004158 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004159 continue;
4160 }
4161
Eric Laurent83efe1c2017-07-09 16:51:08 -07004162 ALOGV("opening output for device %08x with params %s profile %p name %s",
4163 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004164 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004165 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004166 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4167 config.sample_rate = desc->mSamplingRate;
4168 config.channel_mask = desc->mChannelMask;
4169 config.format = desc->mFormat;
4170 config.offload_info.sample_rate = desc->mSamplingRate;
4171 config.offload_info.channel_mask = desc->mChannelMask;
4172 config.offload_info.format = desc->mFormat;
4173 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004174 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004175 &output,
4176 &config,
4177 &desc->mDevice,
4178 address,
4179 &desc->mLatency,
4180 desc->mFlags);
4181 if (status == NO_ERROR) {
4182 desc->mSamplingRate = config.sample_rate;
4183 desc->mChannelMask = config.channel_mask;
4184 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004185
Eric Laurentd4692962014-05-05 18:13:44 -07004186 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004187 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004188 char *param = audio_device_address_to_parameter(device, address);
4189 mpClientInterface->setParameters(output, String8(param));
4190 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
Phil Burk00eeb322016-03-31 12:41:00 -07004192 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004193 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004194 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004195 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004196 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004197 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004198 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004199 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004200 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004201 config.offload_info.sample_rate = config.sample_rate;
4202 config.offload_info.channel_mask = config.channel_mask;
4203 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004204 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004205 &output,
4206 &config,
4207 &desc->mDevice,
4208 address,
4209 &desc->mLatency,
4210 desc->mFlags);
4211 if (status == NO_ERROR) {
4212 desc->mSamplingRate = config.sample_rate;
4213 desc->mChannelMask = config.channel_mask;
4214 desc->mFormat = config.format;
4215 } else {
4216 output = AUDIO_IO_HANDLE_NONE;
4217 }
Eric Laurentd4692962014-05-05 18:13:44 -07004218 }
4219
Eric Laurentcf2c0212014-07-25 16:20:43 -07004220 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004221 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004222 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004223 sp<AudioPolicyMix> policyMix;
4224 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004225 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4226 address.string());
4227 }
François Gaffie036e1e92015-03-19 10:16:24 +01004228 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004229 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004230
Eric Laurent87ffa392015-05-22 10:32:38 -07004231 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4232 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004233 // no duplicated output for direct outputs and
4234 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004235 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004236
Eric Laurentd4692962014-05-05 18:13:44 -07004237 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004238 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004239
Eric Laurentd4692962014-05-05 18:13:44 -07004240 //TODO: configure audio effect output stage here
4241
4242 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004243 duplicatedOutput =
4244 mpClientInterface->openDuplicateOutput(output,
4245 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004246 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004247 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004248 sp<SwAudioOutputDescriptor> dupOutputDesc =
4249 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4250 dupOutputDesc->mOutput1 = mPrimaryOutput;
4251 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004252 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4253 dupOutputDesc->mFormat = desc->mFormat;
4254 dupOutputDesc->mChannelMask = desc->mChannelMask;
4255 dupOutputDesc->mLatency = desc->mLatency;
4256 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004257 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004258 } else {
4259 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004260 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004261 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004262 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004263 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004264 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004265 }
Eric Laurente552edb2014-03-10 17:42:56 -07004266 }
4267 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004268 } else {
4269 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004270 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004271 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004273 profiles.removeAt(profile_index);
4274 profile_index--;
4275 } else {
4276 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004277 // Load digital format info only for digital devices
4278 if (audio_device_is_digital(device)) {
4279 devDesc->importAudioPort(profile);
4280 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004281
François Gaffie53615e22015-03-19 09:24:12 +01004282 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004283 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4284 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004285 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004286 NULL/*patch handle*/, address.string());
4287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 ALOGV("checkOutputsForDevice(): adding output %d", output);
4289 }
4290 }
4291
4292 if (profiles.isEmpty()) {
4293 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4294 return BAD_VALUE;
4295 }
Eric Laurentd4692962014-05-05 18:13:44 -07004296 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004297 // check if one opened output is not needed any more after disconnecting one device
4298 for (size_t i = 0; i < mOutputs.size(); i++) {
4299 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004300 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004301 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004302 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004303 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004304 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004305 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004306 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4307 mOutputs.keyAt(i));
4308 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004309 }
Eric Laurente552edb2014-03-10 17:42:56 -07004310 }
4311 }
Eric Laurentd4692962014-05-05 18:13:44 -07004312 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004313 for (size_t i = 0; i < mHwModules.size(); i++)
4314 {
4315 if (mHwModules[i]->mHandle == 0) {
4316 continue;
4317 }
4318 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4319 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004320 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004321 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004322 ALOGV("checkOutputsForDevice(): "
4323 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004324 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004325 }
4326 }
4327 }
4328 }
4329 return NO_ERROR;
4330}
4331
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004332status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004333 audio_policy_dev_state_t state,
4334 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004335 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004336{
Paul McLean9080a4c2015-06-18 08:24:02 -07004337 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004338 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004339
4340 if (audio_device_is_digital(device)) {
4341 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004342 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004343 }
4344
Eric Laurentd4692962014-05-05 18:13:44 -07004345 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4346 // first list already open inputs that can be routed to this device
4347 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4348 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004349 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004350 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4351 inputs.add(mInputs.keyAt(input_index));
4352 }
4353 }
4354
4355 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004356 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004357 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4358 {
4359 if (mHwModules[module_idx]->mHandle == 0) {
4360 continue;
4361 }
4362 for (size_t profile_index = 0;
4363 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4364 profile_index++)
4365 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004366 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4367
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004368 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004369 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004370 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004371 profiles.add(profile);
4372 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4373 profile_index, module_idx);
4374 }
Eric Laurentd4692962014-05-05 18:13:44 -07004375 }
4376 }
4377 }
4378
4379 if (profiles.isEmpty() && inputs.isEmpty()) {
4380 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4381 return BAD_VALUE;
4382 }
4383
4384 // open inputs for matching profiles if needed. Direct inputs are also opened to
4385 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4386 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4387
Eric Laurent1c333e22014-05-20 10:48:17 -07004388 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004389 // nothing to do if one input is already opened for this profile
4390 size_t input_index;
4391 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4392 desc = mInputs.valueAt(input_index);
4393 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004394 if (audio_device_is_digital(device)) {
4395 devDesc->importAudioPort(profile);
4396 }
Eric Laurentd4692962014-05-05 18:13:44 -07004397 break;
4398 }
4399 }
4400 if (input_index != mInputs.size()) {
4401 continue;
4402 }
4403
4404 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4405 desc = new AudioInputDescriptor(profile);
4406 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004407 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4408 config.sample_rate = desc->mSamplingRate;
4409 config.channel_mask = desc->mChannelMask;
4410 config.format = desc->mFormat;
4411 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004412
4413 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4414 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4415
Eric Laurent322b4d22015-04-03 15:57:54 -07004416 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004417 &input,
4418 &config,
4419 &desc->mDevice,
4420 address,
4421 AUDIO_SOURCE_MIC,
4422 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004423
Eric Laurentcf2c0212014-07-25 16:20:43 -07004424 if (status == NO_ERROR) {
4425 desc->mSamplingRate = config.sample_rate;
4426 desc->mChannelMask = config.channel_mask;
4427 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004428
Eric Laurentd4692962014-05-05 18:13:44 -07004429 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004430 char *param = audio_device_address_to_parameter(device, address);
4431 mpClientInterface->setParameters(input, String8(param));
4432 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004433 }
Phil Burk00eeb322016-03-31 12:41:00 -07004434 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004435 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004436 ALOGW("checkInputsForDevice() direct input missing param");
4437 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004438 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004439 }
4440
4441 if (input != 0) {
4442 addInput(input, desc);
4443 }
4444 } // endif input != 0
4445
Eric Laurentcf2c0212014-07-25 16:20:43 -07004446 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004447 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004448 profiles.removeAt(profile_index);
4449 profile_index--;
4450 } else {
4451 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004452 if (audio_device_is_digital(device)) {
4453 devDesc->importAudioPort(profile);
4454 }
Eric Laurentd4692962014-05-05 18:13:44 -07004455 ALOGV("checkInputsForDevice(): adding input %d", input);
4456 }
4457 } // end scan profiles
4458
4459 if (profiles.isEmpty()) {
4460 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4461 return BAD_VALUE;
4462 }
4463 } else {
4464 // Disconnect
4465 // check if one opened input is not needed any more after disconnecting one device
4466 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4467 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004468 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004469 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4470 mInputs.keyAt(input_index));
4471 inputs.add(mInputs.keyAt(input_index));
4472 }
4473 }
4474 // Clear any profiles associated with the disconnected device.
4475 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4476 if (mHwModules[module_index]->mHandle == 0) {
4477 continue;
4478 }
4479 for (size_t profile_index = 0;
4480 profile_index < mHwModules[module_index]->mInputProfiles.size();
4481 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004482 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004483 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004484 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004485 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004486 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004487 }
4488 }
4489 }
4490 } // end disconnect
4491
4492 return NO_ERROR;
4493}
4494
4495
Eric Laurente0720872014-03-11 09:30:41 -07004496void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004497{
4498 ALOGV("closeOutput(%d)", output);
4499
Eric Laurentc75307b2015-03-17 15:29:32 -07004500 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004501 if (outputDesc == NULL) {
4502 ALOGW("closeOutput() unknown output %d", output);
4503 return;
4504 }
François Gaffie036e1e92015-03-19 10:16:24 +01004505 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004506
Eric Laurente552edb2014-03-10 17:42:56 -07004507 // look for duplicated outputs connected to the output being removed.
4508 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004509 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 if (dupOutputDesc->isDuplicated() &&
4511 (dupOutputDesc->mOutput1 == outputDesc ||
4512 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004513 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004514 if (dupOutputDesc->mOutput1 == outputDesc) {
4515 outputDesc2 = dupOutputDesc->mOutput2;
4516 } else {
4517 outputDesc2 = dupOutputDesc->mOutput1;
4518 }
4519 // As all active tracks on duplicated output will be deleted,
4520 // and as they were also referenced on the other output, the reference
4521 // count for their stream type must be adjusted accordingly on
4522 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004523 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004524 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004525 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004526 }
4527 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4528 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4529
4530 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004531 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004532 }
4533 }
4534
Eric Laurent05b90f82014-08-27 15:32:29 -07004535 nextAudioPortGeneration();
4536
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004537 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004538 if (index >= 0) {
4539 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004540 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004541 mAudioPatches.removeItemsAt(index);
4542 mpClientInterface->onAudioPatchListUpdate();
4543 }
4544
Eric Laurente552edb2014-03-10 17:42:56 -07004545 AudioParameter param;
4546 param.add(String8("closing"), String8("true"));
4547 mpClientInterface->setParameters(output, param.toString());
4548
4549 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004550 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004551 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004552}
4553
4554void AudioPolicyManager::closeInput(audio_io_handle_t input)
4555{
4556 ALOGV("closeInput(%d)", input);
4557
4558 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4559 if (inputDesc == NULL) {
4560 ALOGW("closeInput() unknown input %d", input);
4561 return;
4562 }
4563
Eric Laurent6a94d692014-05-20 11:18:06 -07004564 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004565
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004566 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004567 if (index >= 0) {
4568 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004569 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004570 mAudioPatches.removeItemsAt(index);
4571 mpClientInterface->onAudioPatchListUpdate();
4572 }
4573
4574 mpClientInterface->closeInput(input);
4575 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004576}
4577
Eric Laurentc75307b2015-03-17 15:29:32 -07004578SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4579 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004580 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004581{
4582 SortedVector<audio_io_handle_t> outputs;
4583
4584 ALOGVV("getOutputsForDevice() device %04x", device);
4585 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004586 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004587 i, openOutputs.valueAt(i)->isDuplicated(),
4588 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004589 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4590 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4591 outputs.add(openOutputs.keyAt(i));
4592 }
4593 }
4594 return outputs;
4595}
4596
Eric Laurente0720872014-03-11 09:30:41 -07004597bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004598 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004599{
4600 if (outputs1.size() != outputs2.size()) {
4601 return false;
4602 }
4603 for (size_t i = 0; i < outputs1.size(); i++) {
4604 if (outputs1[i] != outputs2[i]) {
4605 return false;
4606 }
4607 }
4608 return true;
4609}
4610
Eric Laurente0720872014-03-11 09:30:41 -07004611void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004612{
4613 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4614 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4615 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4616 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4617
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004618 // also take into account external policy-related changes: add all outputs which are
4619 // associated with policies in the "before" and "after" output vectors
4620 ALOGVV("checkOutputForStrategy(): policy related outputs");
4621 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004622 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004623 if (desc != 0 && desc->mPolicyMix != NULL) {
4624 srcOutputs.add(desc->mIoHandle);
4625 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4626 }
4627 }
4628 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004629 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004630 if (desc != 0 && desc->mPolicyMix != NULL) {
4631 dstOutputs.add(desc->mIoHandle);
4632 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4633 }
4634 }
4635
Eric Laurente552edb2014-03-10 17:42:56 -07004636 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4637 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4638 strategy, srcOutputs[0], dstOutputs[0]);
4639 // mute strategy while moving tracks from one output to another
4640 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004641 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004642 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004643 setStrategyMute(strategy, true, desc);
4644 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004645 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004646 sp<AudioSourceDescriptor> source =
4647 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4648 if (source != 0){
4649 connectAudioSource(source);
4650 }
Eric Laurente552edb2014-03-10 17:42:56 -07004651 }
4652
4653 // Move effects associated to this strategy from previous output to new output
4654 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004655 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004656 }
4657 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004658 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004659 if (getStrategy((audio_stream_type_t)i) == strategy) {
4660 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 }
4662 }
4663 }
4664}
4665
Eric Laurente0720872014-03-11 09:30:41 -07004666void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004667{
François Gaffie2110e042015-03-24 08:41:51 +01004668 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004669 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004670 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004671 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004672 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004673 checkOutputForStrategy(STRATEGY_SONIFICATION);
4674 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004675 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004676 checkOutputForStrategy(STRATEGY_MEDIA);
4677 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004678 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004679}
4680
Eric Laurente0720872014-03-11 09:30:41 -07004681void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004682{
François Gaffie53615e22015-03-19 09:24:12 +01004683 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lata32371762018-01-31 20:24:23 -08004684 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004685 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004686 return;
4687 }
4688
Eric Laurent3a4311c2014-03-17 12:00:47 -07004689 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004690 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4691 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4692 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004693
4694 // if suspended, restore A2DP output if:
4695 // ((SCO device is NOT connected) ||
4696 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4697 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004698 //
Eric Laurentf732e072016-08-03 19:30:28 -07004699 // if not suspended, suspend A2DP output if:
4700 // (SCO device is connected) &&
4701 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4702 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004703 //
4704 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004705 if (!isScoConnected ||
4706 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4707 AUDIO_POLICY_FORCE_BT_SCO) &&
4708 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4709 AUDIO_POLICY_FORCE_BT_SCO) &&
4710 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004711 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004712
4713 mpClientInterface->restoreOutput(a2dpOutput);
4714 mA2dpSuspended = false;
4715 }
4716 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004717 if (isScoConnected &&
4718 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4719 AUDIO_POLICY_FORCE_BT_SCO) ||
4720 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4721 AUDIO_POLICY_FORCE_BT_SCO) ||
4722 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004723 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004724
4725 mpClientInterface->suspendOutput(a2dpOutput);
4726 mA2dpSuspended = true;
4727 }
4728 }
4729}
4730
Eric Laurentc75307b2015-03-17 15:29:32 -07004731audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4732 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
4734 audio_devices_t device = AUDIO_DEVICE_NONE;
4735
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004736 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 if (index >= 0) {
4738 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4739 if (patchDesc->mUid != mUidCached) {
4740 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004741 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 return outputDesc->device();
4743 }
4744 }
4745
Eric Laurente552edb2014-03-10 17:42:56 -07004746 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004747 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004748 // use device for strategy enforced audible
4749 // 2: we are in call or the strategy phone is active on the output:
4750 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004751 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004752 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004753 // 4: the strategy for enforced audible is active but not enforced on the output:
4754 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004755 // 5: the strategy accessibility is active on the output:
4756 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004757 // 6: the strategy "respectful" sonification is active on the output:
4758 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004759 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004760 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004761 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004762 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004763 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004764 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004765 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004766 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004767 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4768 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004769 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004770 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004771 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004772 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004773 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4774 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004775 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4776 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004777 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004778 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004779 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004781 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004782 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004783 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004784 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004785 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004786 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004787 }
4788
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 ALOGV("getNewOutputDevice() selected device %x", device);
4790 return device;
4791}
4792
Eric Laurentfb66dd92016-01-28 18:32:03 -08004793audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004794{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004795 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004796
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004797 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 if (index >= 0) {
4799 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4800 if (patchDesc->mUid != mUidCached) {
4801 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004802 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 return inputDesc->mDevice;
4804 }
4805 }
4806
Eric Laurentfb66dd92016-01-28 18:32:03 -08004807 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4808 if (isInCall()) {
4809 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4810 } else if (source != AUDIO_SOURCE_DEFAULT) {
4811 device = getDeviceAndMixForInputSource(source);
4812 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004813
Eric Laurente552edb2014-03-10 17:42:56 -07004814 return device;
4815}
4816
Eric Laurent794fde22016-03-11 09:50:45 -08004817bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4818 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004819 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004820}
4821
Eric Laurente0720872014-03-11 09:30:41 -07004822uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 return (uint32_t)getStrategy(stream);
4824}
4825
Eric Laurente0720872014-03-11 09:30:41 -07004826audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004827 // By checking the range of stream before calling getStrategy, we avoid
4828 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4829 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004830 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 return AUDIO_DEVICE_NONE;
4832 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004833 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004834 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4835 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004836 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 }
Eric Laurent794fde22016-03-11 09:50:45 -08004838 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004839 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004840 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004841 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4842 for (size_t i = 0; i < outputs.size(); i++) {
4843 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004844 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004845 curDevices |= outputDesc->device();
4846 }
4847 }
4848 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004849 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004850
4851 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4852 and doesn't really need to.*/
4853 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4854 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4855 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4856 }
Eric Laurente552edb2014-03-10 17:42:56 -07004857 return devices;
4858}
4859
François Gaffie2110e042015-03-24 08:41:51 +01004860routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4861{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004862 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004863 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004864}
4865
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004866uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4867 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004868 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4869 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4870 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004871 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4872 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4873 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004874 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004875 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004876}
4877
Eric Laurente0720872014-03-11 09:30:41 -07004878void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004879 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004880 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004881 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4882 updateDevicesAndOutputs();
4883 break;
4884 default:
4885 break;
4886 }
4887}
4888
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004889uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004890
4891 // skip beacon mute management if a dedicated TTS output is available
4892 if (mTtsOutputAvailable) {
4893 return 0;
4894 }
4895
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004896 switch(event) {
4897 case STARTING_OUTPUT:
4898 mBeaconMuteRefCount++;
4899 break;
4900 case STOPPING_OUTPUT:
4901 if (mBeaconMuteRefCount > 0) {
4902 mBeaconMuteRefCount--;
4903 }
4904 break;
4905 case STARTING_BEACON:
4906 mBeaconPlayingRefCount++;
4907 break;
4908 case STOPPING_BEACON:
4909 if (mBeaconPlayingRefCount > 0) {
4910 mBeaconPlayingRefCount--;
4911 }
4912 break;
4913 }
4914
4915 if (mBeaconMuteRefCount > 0) {
4916 // any playback causes beacon to be muted
4917 return setBeaconMute(true);
4918 } else {
4919 // no other playback: unmute when beacon starts playing, mute when it stops
4920 return setBeaconMute(mBeaconPlayingRefCount == 0);
4921 }
4922}
4923
4924uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4925 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4926 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4927 // keep track of muted state to avoid repeating mute/unmute operations
4928 if (mBeaconMuted != mute) {
4929 // mute/unmute AUDIO_STREAM_TTS on all outputs
4930 ALOGV("\t muting %d", mute);
4931 uint32_t maxLatency = 0;
4932 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004933 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004934 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004935 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004936 0 /*delay*/, AUDIO_DEVICE_NONE);
4937 const uint32_t latency = desc->latency() * 2;
4938 if (latency > maxLatency) {
4939 maxLatency = latency;
4940 }
4941 }
4942 mBeaconMuted = mute;
4943 return maxLatency;
4944 }
4945 return 0;
4946}
4947
Eric Laurente0720872014-03-11 09:30:41 -07004948audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004949 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004950{
Paul McLeanaa981192015-03-21 09:55:15 -07004951 // Routing
4952 // see if we have an explicit route
4953 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4954 // (getStrategy(stream)).
4955 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004956 // and activity count is non-zero and the device in the route descriptor is available
4957 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004958 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4959 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004960 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004961 if ((routeStrategy == strategy) && route->isActive() &&
4962 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004963 return route->mDeviceDescriptor->type();
4964 }
4965 }
4966
Eric Laurente552edb2014-03-10 17:42:56 -07004967 if (fromCache) {
4968 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4969 strategy, mDeviceForStrategy[strategy]);
4970 return mDeviceForStrategy[strategy];
4971 }
François Gaffie2110e042015-03-24 08:41:51 +01004972 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004973}
4974
Eric Laurente0720872014-03-11 09:30:41 -07004975void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004976{
4977 for (int i = 0; i < NUM_STRATEGIES; i++) {
4978 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4979 }
4980 mPreviousOutputs = mOutputs;
4981}
4982
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004983uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004984 audio_devices_t prevDevice,
4985 uint32_t delayMs)
4986{
4987 // mute/unmute strategies using an incompatible device combination
4988 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4989 // if unmuting, unmute only after the specified delay
4990 if (outputDesc->isDuplicated()) {
4991 return 0;
4992 }
4993
4994 uint32_t muteWaitMs = 0;
4995 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004996 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004997
4998 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4999 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005000 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005001 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5002 bool doMute = false;
5003
5004 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5005 doMute = true;
5006 outputDesc->mStrategyMutedByDevice[i] = true;
5007 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5008 doMute = true;
5009 outputDesc->mStrategyMutedByDevice[i] = false;
5010 }
Eric Laurent99401132014-05-07 19:48:15 -07005011 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005012 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005013 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005014 // skip output if it does not share any device with current output
5015 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5016 == AUDIO_DEVICE_NONE) {
5017 continue;
5018 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005019 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005020 mute ? "muting" : "unmuting", i, curDevice);
5021 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005022 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005023 if (mute) {
5024 // FIXME: should not need to double latency if volume could be applied
5025 // immediately by the audioflinger mixer. We must account for the delay
5026 // between now and the next time the audioflinger thread for this output
5027 // will process a buffer (which corresponds to one buffer size,
5028 // usually 1/2 or 1/4 of the latency).
5029 if (muteWaitMs < desc->latency() * 2) {
5030 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005031 }
5032 }
5033 }
5034 }
5035 }
5036 }
5037
Eric Laurent99401132014-05-07 19:48:15 -07005038 // temporary mute output if device selection changes to avoid volume bursts due to
5039 // different per device volumes
5040 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005041 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5042 // temporary mute duration is conservatively set to 4 times the reported latency
5043 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5044 if (muteWaitMs < tempMuteWaitMs) {
5045 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005046 }
Eric Laurentdc462862016-07-19 12:29:53 -07005047
Eric Laurent99401132014-05-07 19:48:15 -07005048 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005049 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005050 // make sure that we do not start the temporary mute period too early in case of
5051 // delayed device change
5052 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005054 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005055 }
5056 }
5057 }
5058
Eric Laurente552edb2014-03-10 17:42:56 -07005059 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5060 if (muteWaitMs > delayMs) {
5061 muteWaitMs -= delayMs;
5062 usleep(muteWaitMs * 1000);
5063 return muteWaitMs;
5064 }
5065 return 0;
5066}
5067
Eric Laurentc75307b2015-03-17 15:29:32 -07005068uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005069 audio_devices_t device,
5070 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005072 audio_patch_handle_t *patchHandle,
5073 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005074{
Eric Laurentc75307b2015-03-17 15:29:32 -07005075 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005076 AudioParameter param;
5077 uint32_t muteWaitMs;
5078
5079 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005080 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5081 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005082 return muteWaitMs;
5083 }
5084 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5085 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005086 if ((device != AUDIO_DEVICE_NONE) &&
5087 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005088 return 0;
5089 }
5090
5091 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005092 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005093
5094 audio_devices_t prevDevice = outputDesc->mDevice;
5095
Paul McLeanaa981192015-03-21 09:55:15 -07005096 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005097
5098 if (device != AUDIO_DEVICE_NONE) {
5099 outputDesc->mDevice = device;
5100 }
5101 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5102
5103 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005104 // the requested device is AUDIO_DEVICE_NONE
5105 // OR the requested device is the same as current device
5106 // AND force is not specified
5107 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005108 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005109 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5110 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005111 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005113 return muteWaitMs;
5114 }
5115
5116 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005117
Eric Laurente552edb2014-03-10 17:42:56 -07005118 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005120 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005121 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005122 DeviceVector deviceList;
5123 if ((address == NULL) || (strlen(address) == 0)) {
5124 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5125 } else {
5126 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5127 }
5128
Eric Laurent1c333e22014-05-20 10:48:17 -07005129 if (!deviceList.isEmpty()) {
5130 struct audio_patch patch;
5131 outputDesc->toAudioPortConfig(&patch.sources[0]);
5132 patch.num_sources = 1;
5133 patch.num_sinks = 0;
5134 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5135 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005136 patch.num_sinks++;
5137 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005138 ssize_t index;
5139 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5140 index = mAudioPatches.indexOfKey(*patchHandle);
5141 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005142 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 }
5144 sp< AudioPatch> patchDesc;
5145 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5146 if (index >= 0) {
5147 patchDesc = mAudioPatches.valueAt(index);
5148 afPatchHandle = patchDesc->mAfPatchHandle;
5149 }
5150
Eric Laurent1c333e22014-05-20 10:48:17 -07005151 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005152 &afPatchHandle,
5153 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005154 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5155 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005157 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005158 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005159 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 addAudioPatch(patchDesc->mHandle, patchDesc);
5161 } else {
5162 patchDesc->mPatch = patch;
5163 }
5164 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 if (patchHandle) {
5166 *patchHandle = patchDesc->mHandle;
5167 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005168 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005169 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005170 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005171 }
5172 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005173
5174 // inform all input as well
5175 for (size_t i = 0; i < mInputs.size(); i++) {
5176 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005177 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005178 AudioParameter inputCmd = AudioParameter();
5179 ALOGV("%s: inform input %d of device:%d", __func__,
5180 inputDescriptor->mIoHandle, device);
5181 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5182 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5183 inputCmd.toString(),
5184 delayMs);
5185 }
5186 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005187 }
Eric Laurente552edb2014-03-10 17:42:56 -07005188
5189 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005191
5192 return muteWaitMs;
5193}
5194
Eric Laurentc75307b2015-03-17 15:29:32 -07005195status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 int delayMs,
5197 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005198{
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 ssize_t index;
5200 if (patchHandle) {
5201 index = mAudioPatches.indexOfKey(*patchHandle);
5202 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005203 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005204 }
5205 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005206 return INVALID_OPERATION;
5207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5209 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005210 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005211 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005212 removeAudioPatch(patchDesc->mHandle);
5213 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005214 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 return status;
5216}
5217
5218status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5219 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 bool force,
5221 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005222{
5223 status_t status = NO_ERROR;
5224
Eric Laurent1f2f2232014-06-02 12:01:23 -07005225 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005226 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5227 inputDesc->mDevice = device;
5228
5229 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5230 if (!deviceList.isEmpty()) {
5231 struct audio_patch patch;
5232 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005233 // AUDIO_SOURCE_HOTWORD is for internal use only:
5234 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005235 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005236 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005237 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5238 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 patch.num_sinks = 1;
5240 //only one input device for now
5241 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 ssize_t index;
5244 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5245 index = mAudioPatches.indexOfKey(*patchHandle);
5246 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005247 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 }
5249 sp< AudioPatch> patchDesc;
5250 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5251 if (index >= 0) {
5252 patchDesc = mAudioPatches.valueAt(index);
5253 afPatchHandle = patchDesc->mAfPatchHandle;
5254 }
5255
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005258 0);
5259 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005260 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005261 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005263 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005264 addAudioPatch(patchDesc->mHandle, patchDesc);
5265 } else {
5266 patchDesc->mPatch = patch;
5267 }
5268 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 if (patchHandle) {
5270 *patchHandle = patchDesc->mHandle;
5271 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005272 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005274 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 }
5276 }
5277 }
5278 return status;
5279}
5280
Eric Laurent6a94d692014-05-20 11:18:06 -07005281status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5282 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005283{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005284 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 ssize_t index;
5286 if (patchHandle) {
5287 index = mAudioPatches.indexOfKey(*patchHandle);
5288 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005289 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 }
5291 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005292 return INVALID_OPERATION;
5293 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5295 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005297 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 removeAudioPatch(patchDesc->mHandle);
5299 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005300 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005301 return status;
5302}
5303
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005304sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005305 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005306 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005307 audio_format_t& format,
5308 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005309 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005310{
5311 // Choose an input profile based on the requested capture parameters: select the first available
5312 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005313 //
5314 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5315 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005316
5317 for (size_t i = 0; i < mHwModules.size(); i++)
5318 {
5319 if (mHwModules[i]->mHandle == 0) {
5320 continue;
5321 }
5322 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5323 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005324 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005325 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005326 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005327 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005328 format,
5329 &format /*updatedFormat*/,
5330 channelMask,
5331 &channelMask /*updatedChannelMask*/,
5332 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005333
Eric Laurente552edb2014-03-10 17:42:56 -07005334 return profile;
5335 }
5336 }
5337 }
5338 return NULL;
5339}
5340
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005341
5342audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005343 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005344{
François Gaffie036e1e92015-03-19 10:16:24 +01005345 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5346 audio_devices_t selectedDeviceFromMix =
5347 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005348
François Gaffie036e1e92015-03-19 10:16:24 +01005349 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5350 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005351 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005352 return getDeviceForInputSource(inputSource);
5353}
5354
5355audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5356{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005357 // Routing
5358 // Scan the whole RouteMap to see if we have an explicit route:
5359 // if the input source in the RouteMap is the same as the argument above,
5360 // and activity count is non-zero and the device in the route descriptor is available
5361 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005362 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5363 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005364 if ((inputSource == route->mSource) && route->isActive() &&
5365 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005366 return route->mDeviceDescriptor->type();
5367 }
5368 }
5369
5370 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005371}
5372
Eric Laurente0720872014-03-11 09:30:41 -07005373float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005374 int index,
5375 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005376{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005377 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005378
5379 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5380 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5381 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5382 // the ringtone volume
5383 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5384 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5385 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5386 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5387 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5388 }
5389
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005390 // in-call: always cap earpiece volume by voice volume + some low headroom
5391 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5392 switch (stream) {
5393 case AUDIO_STREAM_SYSTEM:
5394 case AUDIO_STREAM_RING:
5395 case AUDIO_STREAM_MUSIC:
5396 case AUDIO_STREAM_ALARM:
5397 case AUDIO_STREAM_NOTIFICATION:
5398 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5399 case AUDIO_STREAM_DTMF:
5400 case AUDIO_STREAM_ACCESSIBILITY: {
5401 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5402 + IN_CALL_EARPIECE_HEADROOM_DB;
5403 if (volumeDB > maxVoiceVolDb) {
5404 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5405 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5406 volumeDB = maxVoiceVolDb;
5407 }
5408 } break;
5409 default:
5410 break;
5411 }
5412 }
5413
Eric Laurente552edb2014-03-10 17:42:56 -07005414 // if a headset is connected, apply the following rules to ring tones and notifications
5415 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005416 // - always attenuate notifications volume by 6dB
5417 // - attenuate ring tones volume by 6dB unless music is not playing and
5418 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005419 // - if music is playing, always limit the volume to current music volume,
5420 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005421 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005422 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5423 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5424 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005425 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5426 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005427 ((stream_strategy == STRATEGY_SONIFICATION)
5428 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005429 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005430 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005431 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005432 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005433 // when the phone is ringing we must consider that music could have been paused just before
5434 // by the music application and behave as if music was active if the last music track was
5435 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005436 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005437 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005438 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005439 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005440 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005441 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5442 musicDevice),
5443 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005444 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5445 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005446 if (volumeDB > minVolDB) {
5447 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005448 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005449 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005450 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5451 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5452 // on A2DP, also ensure notification volume is not too low compared to media when
5453 // intended to be played
5454 if ((volumeDB > -96.0f) &&
5455 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5456 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5457 stream, device,
5458 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5459 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5460 }
5461 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005462 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5463 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005464 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005465 }
5466 }
5467
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005468 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005469}
5470
Eric Laurente0720872014-03-11 09:30:41 -07005471status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005472 int index,
5473 const sp<AudioOutputDescriptor>& outputDesc,
5474 audio_devices_t device,
5475 int delayMs,
5476 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005477{
Eric Laurente552edb2014-03-10 17:42:56 -07005478 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005479 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005480 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005481 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005482 return NO_ERROR;
5483 }
François Gaffie2110e042015-03-24 08:41:51 +01005484 audio_policy_forced_cfg_t forceUseForComm =
5485 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005486 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005487 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5488 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005489 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005490 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005491 return INVALID_OPERATION;
5492 }
5493
Eric Laurentc75307b2015-03-17 15:29:32 -07005494 if (device == AUDIO_DEVICE_NONE) {
5495 device = outputDesc->device();
5496 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005497
Eric Laurentffbc80f2015-03-18 18:30:19 -07005498 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005499 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005500 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005501 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005502
Eric Laurentffbc80f2015-03-18 18:30:19 -07005503 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005504
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 if (stream == AUDIO_STREAM_VOICE_CALL ||
5506 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005507 float voiceVolume;
5508 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005509 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005510 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005511 } else {
5512 voiceVolume = 1.0;
5513 }
5514
Eric Laurent18fba842016-03-31 14:41:26 -07005515 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005516 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5517 mLastVoiceVolume = voiceVolume;
5518 }
5519 }
5520
5521 return NO_ERROR;
5522}
5523
Eric Laurentc75307b2015-03-17 15:29:32 -07005524void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5525 audio_devices_t device,
5526 int delayMs,
5527 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005528{
Eric Laurentc75307b2015-03-17 15:29:32 -07005529 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005530
Eric Laurent794fde22016-03-11 09:50:45 -08005531 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005532 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005533 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005534 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005535 device,
5536 delayMs,
5537 force);
5538 }
5539}
5540
Eric Laurente0720872014-03-11 09:30:41 -07005541void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005542 bool on,
5543 const sp<AudioOutputDescriptor>& outputDesc,
5544 int delayMs,
5545 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005546{
Eric Laurent72249d52015-06-08 11:12:15 -07005547 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5548 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005549 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005550 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005551 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005552 }
5553 }
5554}
5555
Eric Laurente0720872014-03-11 09:30:41 -07005556void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005557 bool on,
5558 const sp<AudioOutputDescriptor>& outputDesc,
5559 int delayMs,
5560 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005561{
Eric Laurente552edb2014-03-10 17:42:56 -07005562 if (device == AUDIO_DEVICE_NONE) {
5563 device = outputDesc->device();
5564 }
5565
Eric Laurentc75307b2015-03-17 15:29:32 -07005566 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5567 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005568
5569 if (on) {
5570 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005571 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005572 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005573 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005574 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005575 }
5576 }
5577 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5578 outputDesc->mMuteCount[stream]++;
5579 } else {
5580 if (outputDesc->mMuteCount[stream] == 0) {
5581 ALOGV("setStreamMute() unmuting non muted stream!");
5582 return;
5583 }
5584 if (--outputDesc->mMuteCount[stream] == 0) {
5585 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005586 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005587 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005588 device,
5589 delayMs);
5590 }
5591 }
5592}
5593
Eric Laurente0720872014-03-11 09:30:41 -07005594void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005595 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005596{
Eric Laurent87ffa392015-05-22 10:32:38 -07005597 if(!hasPrimaryOutput()) {
5598 return;
5599 }
5600
Eric Laurente552edb2014-03-10 17:42:56 -07005601 // if the stream pertains to sonification strategy and we are in call we must
5602 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5603 // in the device used for phone strategy and play the tone if the selected device does not
5604 // interfere with the device used for phone strategy
5605 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5606 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005607 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005608 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5609 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005611 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5612 stream, starting, outputDesc->mDevice, stateChange);
5613 if (outputDesc->mRefCount[stream]) {
5614 int muteCount = 1;
5615 if (stateChange) {
5616 muteCount = outputDesc->mRefCount[stream];
5617 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005618 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005619 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5620 for (int i = 0; i < muteCount; i++) {
5621 setStreamMute(stream, starting, mPrimaryOutput);
5622 }
5623 } else {
5624 ALOGV("handleIncallSonification() high visibility");
5625 if (outputDesc->device() &
5626 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5627 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5628 for (int i = 0; i < muteCount; i++) {
5629 setStreamMute(stream, starting, mPrimaryOutput);
5630 }
5631 }
5632 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005633 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5634 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005635 } else {
5636 mpClientInterface->stopTone();
5637 }
5638 }
5639 }
5640 }
5641}
5642
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005643audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5644{
5645 // flags to stream type mapping
5646 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5647 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5648 }
5649 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5650 return AUDIO_STREAM_BLUETOOTH_SCO;
5651 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005652 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5653 return AUDIO_STREAM_TTS;
5654 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005655
5656 // usage to stream type mapping
5657 switch (attr->usage) {
5658 case AUDIO_USAGE_MEDIA:
5659 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005660 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005661 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5662 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005663 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5664 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005665 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5666 return AUDIO_STREAM_SYSTEM;
5667 case AUDIO_USAGE_VOICE_COMMUNICATION:
5668 return AUDIO_STREAM_VOICE_CALL;
5669
5670 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5671 return AUDIO_STREAM_DTMF;
5672
5673 case AUDIO_USAGE_ALARM:
5674 return AUDIO_STREAM_ALARM;
5675 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5676 return AUDIO_STREAM_RING;
5677
5678 case AUDIO_USAGE_NOTIFICATION:
5679 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5680 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5681 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5682 case AUDIO_USAGE_NOTIFICATION_EVENT:
5683 return AUDIO_STREAM_NOTIFICATION;
5684
5685 case AUDIO_USAGE_UNKNOWN:
5686 default:
5687 return AUDIO_STREAM_MUSIC;
5688 }
5689}
Eric Laurente83b55d2014-11-14 10:06:21 -08005690
François Gaffie53615e22015-03-19 09:24:12 +01005691bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5692{
Eric Laurente83b55d2014-11-14 10:06:21 -08005693 // has flags that map to a strategy?
5694 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5695 return true;
5696 }
5697
5698 // has known usage?
5699 switch (paa->usage) {
5700 case AUDIO_USAGE_UNKNOWN:
5701 case AUDIO_USAGE_MEDIA:
5702 case AUDIO_USAGE_VOICE_COMMUNICATION:
5703 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5704 case AUDIO_USAGE_ALARM:
5705 case AUDIO_USAGE_NOTIFICATION:
5706 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5707 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5708 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5709 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5710 case AUDIO_USAGE_NOTIFICATION_EVENT:
5711 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5712 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5713 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5714 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005715 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005716 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005717 break;
5718 default:
5719 return false;
5720 }
5721 return true;
5722}
5723
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005724bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005725 routing_strategy strategy, uint32_t inPastMs,
5726 nsecs_t sysTime) const
5727{
5728 if ((sysTime == 0) && (inPastMs != 0)) {
5729 sysTime = systemTime();
5730 }
Eric Laurent794fde22016-03-11 09:50:45 -08005731 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005732 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5733 (NUM_STRATEGIES == strategy)) &&
5734 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5735 return true;
5736 }
5737 }
5738 return false;
5739}
5740
François Gaffie2110e042015-03-24 08:41:51 +01005741audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5742{
5743 return mEngine->getForceUse(usage);
5744}
5745
5746bool AudioPolicyManager::isInCall()
5747{
5748 return isStateInCall(mEngine->getPhoneState());
5749}
5750
5751bool AudioPolicyManager::isStateInCall(int state)
5752{
5753 return is_state_in_call(state);
5754}
5755
Eric Laurentd60560a2015-04-10 11:31:20 -07005756void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5757{
5758 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5759 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5760 if (sourceDesc->mDevice->equals(deviceDesc)) {
5761 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5762 stopAudioSource(sourceDesc->getHandle());
5763 }
5764 }
5765
5766 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5767 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5768 bool release = false;
5769 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5770 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5771 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5772 source->ext.device.type == deviceDesc->type()) {
5773 release = true;
5774 }
5775 }
5776 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5777 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5778 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5779 sink->ext.device.type == deviceDesc->type()) {
5780 release = true;
5781 }
5782 }
5783 if (release) {
5784 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5785 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5786 }
5787 }
5788}
5789
Phil Burk09bc4612016-02-24 15:58:15 -08005790// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005791void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5792 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005793 // TODO Set this based on Config properties.
5794 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005795
5796 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5797 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005798 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005799
5800 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005801 bool supportsAC3 = false;
5802 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005803 bool supportsIEC61937 = false;
5804 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5805 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005806 switch (format) {
5807 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005808 supportsAC3 = true;
5809 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005810 case AUDIO_FORMAT_E_AC3:
5811 case AUDIO_FORMAT_DTS:
5812 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005813 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005814 break;
5815 case AUDIO_FORMAT_IEC61937:
5816 supportsIEC61937 = true;
5817 break;
5818 default:
5819 break;
5820 }
5821 }
Phil Burk09bc4612016-02-24 15:58:15 -08005822
5823 // Modify formats based on surround preferences.
5824 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005825 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5826 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5827 // Remove surround sound related formats.
5828 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5829 audio_format_t format = formats[formatIndex];
5830 switch(format) {
5831 case AUDIO_FORMAT_AC3:
5832 case AUDIO_FORMAT_E_AC3:
5833 case AUDIO_FORMAT_DTS:
5834 case AUDIO_FORMAT_DTS_HD:
5835 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005836 formats.removeAt(formatIndex);
5837 break;
5838 default:
5839 formatIndex++; // keep it
5840 break;
5841 }
Phil Burk09bc4612016-02-24 15:58:15 -08005842 }
Phil Burk07ac1142016-03-25 13:39:29 -07005843 supportsAC3 = false;
5844 supportsOtherSurround = false;
5845 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005846 }
Phil Burk07ac1142016-03-25 13:39:29 -07005847 } else { // AUTO or ALWAYS
5848 // Most TVs support AC3 even if they do not report it in the EDID.
5849 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5850 && !supportsAC3) {
5851 formats.add(AUDIO_FORMAT_AC3);
5852 supportsAC3 = true;
5853 }
5854
5855 // If ALWAYS, add support for raw surround formats if all are missing.
5856 // This assumes that if any of these formats are reported by the HAL
5857 // then the report is valid and should not be modified.
5858 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5859 && !supportsOtherSurround) {
5860 formats.add(AUDIO_FORMAT_E_AC3);
5861 formats.add(AUDIO_FORMAT_DTS);
5862 formats.add(AUDIO_FORMAT_DTS_HD);
5863 supportsOtherSurround = true;
5864 }
5865
5866 // Add support for IEC61937 if any raw surround supported.
5867 // The HAL could do this but add it here, just in case.
5868 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5869 formats.add(AUDIO_FORMAT_IEC61937);
5870 supportsIEC61937 = true;
5871 }
Phil Burk09bc4612016-02-24 15:58:15 -08005872 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005873}
5874
5875// Modify the list of channel masks supported.
5876void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5877 ChannelsVector &channelMasks = *channelMasksPtr;
5878 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5879 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5880
5881 // If NEVER, then remove support for channelMasks > stereo.
5882 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5883 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5884 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5885 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5886 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5887 channelMasks.removeAt(maskIndex);
5888 } else {
5889 maskIndex++;
5890 }
5891 }
5892 // If ALWAYS, then make sure we at least support 5.1
5893 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5894 bool supports5dot1 = false;
5895 // Are there any channel masks that can be considered "surround"?
5896 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5897 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5898 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5899 supports5dot1 = true;
5900 break;
5901 }
5902 }
5903 // If not then add 5.1 support.
5904 if (!supports5dot1) {
5905 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5906 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5907 }
Phil Burk09bc4612016-02-24 15:58:15 -08005908 }
5909}
5910
Phil Burk00eeb322016-03-31 12:41:00 -07005911void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5912 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005913 AudioProfileVector &profiles)
5914{
5915 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005916
François Gaffie112b0af2015-11-19 16:13:25 +01005917 // Format MUST be checked first to update the list of AudioProfile
5918 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005919 reply = mpClientInterface->getParameters(
5920 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005921 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005922 AudioParameter repliedParameters(reply);
5923 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005924 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005925 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5926 return;
5927 }
Phil Burk09bc4612016-02-24 15:58:15 -08005928 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005929 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005930 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005931 }
Phil Burk09bc4612016-02-24 15:58:15 -08005932 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005933 }
5934 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5935
Eric Laurent20eb3a42016-01-26 18:39:17 -08005936 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005937 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005938 ChannelsVector channelMasks;
5939 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005940 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005941 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005942
5943 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005944 reply = mpClientInterface->getParameters(
5945 ioHandle,
5946 requestedParameters.toString() + ";" +
5947 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005948 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005949 AudioParameter repliedParameters(reply);
5950 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005951 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005952 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005953 }
5954 }
5955 if (profiles.hasDynamicChannelsFor(format)) {
5956 reply = mpClientInterface->getParameters(ioHandle,
5957 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005958 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005959 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005960 AudioParameter repliedParameters(reply);
5961 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005962 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005963 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005964 if (device == AUDIO_DEVICE_OUT_HDMI) {
5965 filterSurroundChannelMasks(&channelMasks);
5966 }
François Gaffie112b0af2015-11-19 16:13:25 +01005967 }
5968 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005969 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005970 }
5971}
Eric Laurentd60560a2015-04-10 11:31:20 -07005972
Eric Laurente552edb2014-03-10 17:42:56 -07005973}; // namespace android