blob: 9d1d468518f501f9558632b92f58efbfe86733dc [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
Eric Laurente552edb2014-03-10 17:42:56 -07001342 return NO_ERROR;
1343}
1344
1345
Eric Laurente0720872014-03-11 09:30:41 -07001346status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001347 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001348 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001349{
1350 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1351 ssize_t index = mOutputs.indexOfKey(output);
1352 if (index < 0) {
1353 ALOGW("stopOutput() unknown output %d", output);
1354 return BAD_VALUE;
1355 }
1356
Eric Laurentc75307b2015-03-17 15:29:32 -07001357 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001358
Eric Laurentc75307b2015-03-17 15:29:32 -07001359 if (outputDesc->mRefCount[stream] == 1) {
1360 // Automatically disable the remote submix input when output is stopped on a
1361 // re routing mix of type MIX_TYPE_RECORDERS
1362 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1363 outputDesc->mPolicyMix != NULL &&
1364 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1365 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1366 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001367 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001368 "remote-submix");
1369 }
1370 }
1371
1372 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001373 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001374 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001375 int activityCount = mOutputRoutes.decRouteActivity(session);
1376 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1377
1378 if (forceDeviceUpdate) {
1379 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1380 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001381 }
1382
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001383 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001384}
1385
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001386status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001387 audio_stream_type_t stream,
1388 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001389{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001390 // always handle stream stop, check which stream type is stopping
1391 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1392
Eric Laurente552edb2014-03-10 17:42:56 -07001393 // handle special case for sonification while in call
1394 if (isInCall()) {
1395 handleIncallSonification(stream, false, false);
1396 }
1397
1398 if (outputDesc->mRefCount[stream] > 0) {
1399 // decrement usage count of this stream on the output
1400 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001401
Eric Laurente552edb2014-03-10 17:42:56 -07001402 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001403 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001404 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001405 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // delay the device switch by twice the latency because stopOutput() is executed when
1407 // the track stop() command is received and at that time the audio track buffer can
1408 // still contain data that needs to be drained. The latency only covers the audio HAL
1409 // and kernel buffers. Also the latency does not always include additional delay in the
1410 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001411 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001412
1413 // force restoring the device selection on other active outputs if it differs from the
1414 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001415 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001416 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001417 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001418 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001419 desc->isActive() &&
1420 outputDesc->sharesHwModuleWith(desc) &&
1421 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001422 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1423 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001424 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001425 newDevice2,
1426 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001427 delayMs);
1428 // re-apply device specific volume if not done by setOutputDevice()
1429 if (!force) {
1430 applyStreamVolumes(desc, newDevice2, delayMs);
1431 }
Eric Laurente552edb2014-03-10 17:42:56 -07001432 }
1433 }
1434 // update the outputs if stopping one with a stream that can affect notification routing
1435 handleNotificationRoutingForStream(stream);
1436 }
Eric Laurent36829f92017-04-07 19:04:42 -07001437 if (stream == AUDIO_STREAM_MUSIC) {
1438 selectOutputForMusicEffects();
1439 }
Eric Laurente552edb2014-03-10 17:42:56 -07001440 return NO_ERROR;
1441 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001442 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001443 return INVALID_OPERATION;
1444 }
1445}
1446
Eric Laurente83b55d2014-11-14 10:06:21 -08001447void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001448 audio_stream_type_t stream __unused,
1449 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001450{
1451 ALOGV("releaseOutput() %d", output);
1452 ssize_t index = mOutputs.indexOfKey(output);
1453 if (index < 0) {
1454 ALOGW("releaseOutput() releasing unknown output %d", output);
1455 return;
1456 }
1457
1458#ifdef AUDIO_POLICY_TEST
1459 int testIndex = testOutputIndex(output);
1460 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001461 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001462 if (outputDesc->isActive()) {
1463 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001464 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001465 mTestOutputs[testIndex] = 0;
1466 }
1467 return;
1468 }
1469#endif //AUDIO_POLICY_TEST
1470
Paul McLeanaa981192015-03-21 09:55:15 -07001471 // Routing
1472 mOutputRoutes.removeRoute(session);
1473
Eric Laurentc75307b2015-03-17 15:29:32 -07001474 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001475 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001476 if (desc->mDirectOpenCount <= 0) {
1477 ALOGW("releaseOutput() invalid open count %d for output %d",
1478 desc->mDirectOpenCount, output);
1479 return;
1480 }
1481 if (--desc->mDirectOpenCount == 0) {
1482 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001483 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001484 }
1485 }
1486}
1487
1488
Eric Laurentcaf7f482014-11-25 17:50:47 -08001489status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1490 audio_io_handle_t *input,
1491 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001492 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001493 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001494 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001495 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001496 input_type_t *inputType,
1497 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001498{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001499 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1500 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001501 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001502
Eric Laurentad2e7b92017-09-14 20:06:42 -07001503 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001504 // handle legacy remote submix case where the address was not always specified
1505 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001506 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001507 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001508 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001509 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001510
Paul McLean466dc8e2015-04-17 13:15:36 -06001511 // Explicit routing?
1512 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001513 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1514 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1515 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1516 deviceDesc = mAvailableInputDevices[i];
1517 break;
1518 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001519 }
1520 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001521 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001522
Eric Laurentad2e7b92017-09-14 20:06:42 -07001523 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1524 // possible
1525 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1526 *input != AUDIO_IO_HANDLE_NONE) {
1527 ssize_t index = mInputs.indexOfKey(*input);
1528 if (index < 0) {
1529 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1530 status = BAD_VALUE;
1531 goto error;
1532 }
1533 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1534 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1535 if (audioSession == 0) {
1536 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1537 status = BAD_VALUE;
1538 goto error;
1539 }
1540 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1541 // The second call is for the first active client and sets the UID. Any further call
1542 // corresponds to a new client and is only permitted from the same UId.
1543 if (audioSession->openCount() == 1) {
1544 audioSession->setUid(uid);
1545 } else if (audioSession->uid() != uid) {
1546 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1547 uid, session, audioSession->uid());
1548 status = INVALID_OPERATION;
1549 goto error;
1550 }
1551 audioSession->changeOpenCount(1);
1552 *inputType = API_INPUT_LEGACY;
1553 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1554 *portId = AudioPort::getNextUniqueId();
1555 }
1556 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1557 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1558 : AUDIO_PORT_HANDLE_NONE;
1559 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1560
1561 return NO_ERROR;
1562 }
1563
1564 *input = AUDIO_IO_HANDLE_NONE;
1565 *inputType = API_INPUT_INVALID;
1566
1567 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1568 inputSource = AUDIO_SOURCE_MIC;
1569 }
1570 halInputSource = inputSource;
1571
1572 // TODO: check for existing client for this port ID
1573 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1574 *portId = AudioPort::getNextUniqueId();
1575 }
1576
1577 audio_devices_t device;
1578
Eric Laurentc447ded2015-01-06 08:47:05 -08001579 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001580 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001581 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1582 if (status != NO_ERROR) {
1583 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001584 }
1585 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001586 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1587 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001588 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001589 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001590 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001591 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001592 status = BAD_VALUE;
1593 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001594 }
Eric Laurentc722f302014-12-10 11:21:49 -08001595 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001596 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001597 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1598 // there is an external policy, but this input is attached to a mix of recorders,
1599 // meaning it receives audio injected into the framework, so the recorder doesn't
1600 // know about it and is therefore considered "legacy"
1601 *inputType = API_INPUT_LEGACY;
1602 } else {
1603 // recording a mix of players defined by an external policy, we're rerouting for
1604 // an external policy
1605 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1606 }
Eric Laurentc722f302014-12-10 11:21:49 -08001607 } else if (audio_is_remote_submix_device(device)) {
1608 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001609 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001610 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1611 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001612 } else {
1613 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001614 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001615
Eric Laurent599c7582015-12-07 18:05:55 -08001616 }
1617
1618 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001619 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001620 policyMix);
1621 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001622 status = INVALID_OPERATION;
1623 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001624 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001625
Eric Laurentad2e7b92017-09-14 20:06:42 -07001626 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001627 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1628 : AUDIO_PORT_HANDLE_NONE;
1629
1630 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1631 *input, *inputType, *selectedDeviceId);
1632
Eric Laurent599c7582015-12-07 18:05:55 -08001633 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001634
1635error:
1636 mInputRoutes.removeRoute(session);
1637 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001638}
1639
1640
1641audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1642 String8 address,
1643 audio_session_t session,
1644 uid_t uid,
1645 audio_source_t inputSource,
1646 uint32_t samplingRate,
1647 audio_format_t format,
1648 audio_channel_mask_t channelMask,
1649 audio_input_flags_t flags,
1650 AudioMix *policyMix)
1651{
1652 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1653 audio_source_t halInputSource = inputSource;
1654 bool isSoundTrigger = false;
1655
1656 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1657 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1658 if (index >= 0) {
1659 input = mSoundTriggerSessions.valueFor(session);
1660 isSoundTrigger = true;
1661 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1662 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1663 } else {
1664 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001665 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001666 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001667 audio_is_linear_pcm(format)) {
1668 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001669 }
1670
Andy Hungf129b032015-04-07 13:45:50 -07001671 // find a compatible input profile (not necessarily identical in parameters)
1672 sp<IOProfile> profile;
1673 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001674 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001675 audio_format_t profileFormat = format;
1676 audio_channel_mask_t profileChannelMask = channelMask;
1677 audio_input_flags_t profileFlags = flags;
1678 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001679 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001680 profileSamplingRate, profileFormat, profileChannelMask,
1681 profileFlags);
1682 if (profile != 0) {
1683 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001684 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1685 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001686 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1687 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1688 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001689 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1690 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001691 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001692 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001693 }
Eric Laurente552edb2014-03-10 17:42:56 -07001694 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001695 // Pick input sampling rate if not specified by client
1696 if (samplingRate == 0) {
1697 samplingRate = profileSamplingRate;
1698 }
Eric Laurente552edb2014-03-10 17:42:56 -07001699
Eric Laurent322b4d22015-04-03 15:57:54 -07001700 if (profile->getModuleHandle() == 0) {
1701 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001702 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001703 }
1704
Eric Laurent599c7582015-12-07 18:05:55 -08001705 sp<AudioSession> audioSession = new AudioSession(session,
1706 inputSource,
1707 format,
1708 samplingRate,
1709 channelMask,
1710 flags,
1711 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001712 isSoundTrigger,
1713 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001714
Eric Laurent74708e72017-04-07 17:13:42 -07001715// FIXME: disable concurrent capture until UI is ready
1716#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001717 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001718 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001719 for (size_t i = 0; i < mInputs.size(); i++) {
1720 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001721 // reuse input if:
1722 // - it shares the same profile
1723 // AND
1724 // - it is not a reroute submix input
1725 // AND
1726 // - it is: not used for sound trigger
1727 // OR
1728 // used for sound trigger and all clients use the same session ID
1729 //
1730 if ((profile == desc->mProfile) &&
1731 (isSoundTrigger == desc->isSoundTrigger()) &&
1732 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001733
1734 sp<AudioSession> as = desc->getAudioSession(session);
1735 if (as != 0) {
1736 // do not allow unmatching properties on same session
1737 if (as->matches(audioSession)) {
1738 as->changeOpenCount(1);
1739 } else {
1740 ALOGW("getInputForDevice() record with different attributes"
1741 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001742 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001743 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001744 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001745 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001746 }
Eric Laurentbb948092017-01-23 18:33:30 -08001747
Eric Laurent555530a2017-02-07 18:17:24 -08001748 // Reuse the already opened input stream on this profile if:
1749 // - the new capture source is background OR
1750 // - the path requested configurations match OR
1751 // - the new source priority is less than the highest source priority on this input
1752 // If the input stream cannot be reused, close it before opening a new stream
1753 // on the same profile for the new client so that the requested path configuration
1754 // can be selected.
1755 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001756 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001757 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001758 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001759 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001760 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001761 reusedInputDesc = desc;
1762 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001763 } else {
1764 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001765 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1766 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001767 }
Eric Laurent599c7582015-12-07 18:05:55 -08001768 }
1769 }
Eric Laurent599c7582015-12-07 18:05:55 -08001770
Eric Laurent555530a2017-02-07 18:17:24 -08001771 if (reusedInputDesc != 0) {
1772 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1773 for (size_t j = 0; j < sessions.size(); j++) {
1774 audio_session_t currentSession = sessions.keyAt(j);
1775 stopInput(reusedInputDesc->mIoHandle, currentSession);
1776 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1777 }
1778 }
Eric Laurent74708e72017-04-07 17:13:42 -07001779#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001780
Eric Laurentcf2c0212014-07-25 16:20:43 -07001781 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001782 config.sample_rate = profileSamplingRate;
1783 config.channel_mask = profileChannelMask;
1784 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001785
Eric Laurente3014102017-05-03 11:15:43 -07001786 if (address == "") {
1787 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1788 // the inputs vector must be of size 1, but we don't want to crash here
1789 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1790 }
1791
Eric Laurent322b4d22015-04-03 15:57:54 -07001792 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001793 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001794 &config,
1795 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001796 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001797 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001798 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001799
1800 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001801 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001802 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001803 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001804 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001805 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1806 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001807 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001808 if (input != AUDIO_IO_HANDLE_NONE) {
1809 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001810 }
Eric Laurent599c7582015-12-07 18:05:55 -08001811 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001812 }
1813
Eric Laurent1f2f2232014-06-02 12:01:23 -07001814 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001815 inputDesc->mSamplingRate = profileSamplingRate;
1816 inputDesc->mFormat = profileFormat;
1817 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001818 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001819 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001820 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001821
Eric Laurent599c7582015-12-07 18:05:55 -08001822 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001823 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001824
Eric Laurent599c7582015-12-07 18:05:55 -08001825 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001826}
1827
Eric Laurentbb948092017-01-23 18:33:30 -08001828//static
1829bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1830{
1831 return (source == AUDIO_SOURCE_HOTWORD) ||
1832 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1833 (source == AUDIO_SOURCE_FM_TUNER);
1834}
1835
Eric Laurentfb66dd92016-01-28 18:32:03 -08001836bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1837 const sp<AudioSession>& audioSession)
1838{
1839 // Do not allow capture if an active voice call is using a software patch and
1840 // the call TX source device is on the same HW module.
1841 // FIXME: would be better to refine to only inputs whose profile connects to the
1842 // call TX device but this information is not in the audio patch
1843 if (mCallTxPatch != 0 &&
1844 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1845 return false;
1846 }
1847
1848 // starting concurrent capture is enabled if:
1849 // 1) capturing for re-routing
1850 // 2) capturing for HOTWORD source
1851 // 3) capturing for FM TUNER source
1852 // 3) All other active captures are either for re-routing or HOTWORD
1853
1854 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001855 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001856 return true;
1857 }
1858
1859 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1860 for (size_t i = 0; i < activeInputs.size(); i++) {
1861 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001862 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001863 !is_virtual_input_device(activeInput->mDevice)) {
1864 return false;
1865 }
1866 }
1867
1868 return true;
1869}
1870
Chris Thornton2b864642017-06-27 21:26:07 -07001871// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1872bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1873 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1874 bool soundTriggerSupportsConcurrentCapture = false;
1875 unsigned int numModules = 0;
1876 struct sound_trigger_module_descriptor* nModules = NULL;
1877
1878 status_t status = SoundTrigger::listModules(nModules, &numModules);
1879 if (status == NO_ERROR && numModules != 0) {
1880 nModules = (struct sound_trigger_module_descriptor*) calloc(
1881 numModules, sizeof(struct sound_trigger_module_descriptor));
1882 if (nModules == NULL) {
1883 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1884 // ram the next time this function is called.
1885 ALOGE("Failed to allocate buffer for module descriptors");
1886 return false;
1887 }
1888
1889 status = SoundTrigger::listModules(nModules, &numModules);
1890 if (status == NO_ERROR) {
1891 soundTriggerSupportsConcurrentCapture = true;
1892 for (size_t i = 0; i < numModules; ++i) {
1893 soundTriggerSupportsConcurrentCapture &=
1894 nModules[i].properties.concurrent_capture;
1895 }
1896 }
1897 free(nModules);
1898 }
1899 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1900 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1901 }
1902 return mSoundTriggerSupportsConcurrentCapture;
1903}
1904
Eric Laurentfb66dd92016-01-28 18:32:03 -08001905
Eric Laurent4dc68062014-07-28 17:26:49 -07001906status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001907 audio_session_t session,
1908 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001909{
1910 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001911 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001912 ssize_t index = mInputs.indexOfKey(input);
1913 if (index < 0) {
1914 ALOGW("startInput() unknown input %d", input);
1915 return BAD_VALUE;
1916 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001917 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001918
Eric Laurent599c7582015-12-07 18:05:55 -08001919 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1920 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001921 ALOGW("startInput() unknown session %d on input %d", session, input);
1922 return BAD_VALUE;
1923 }
1924
Eric Laurent74708e72017-04-07 17:13:42 -07001925// FIXME: disable concurrent capture until UI is ready
1926#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001927 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1928 ALOGW("startInput(%d) failed: other input already started", input);
1929 return INVALID_OPERATION;
1930 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001931
Eric Laurentfb66dd92016-01-28 18:32:03 -08001932 if (isInCall()) {
1933 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1934 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001935 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001936 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001937 }
Eric Laurent74708e72017-04-07 17:13:42 -07001938#else
1939 if (!is_virtual_input_device(inputDesc->mDevice)) {
1940 if (mCallTxPatch != 0 &&
1941 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1942 ALOGW("startInput(%d) failed: call in progress", input);
1943 return INVALID_OPERATION;
1944 }
1945
1946 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1947 for (size_t i = 0; i < activeInputs.size(); i++) {
1948 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1949
1950 if (is_virtual_input_device(activeDesc->mDevice)) {
1951 continue;
1952 }
1953
Eric Laurentcb4dae22017-07-01 19:39:32 -07001954 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1955 activeDesc->getId() == inputDesc->getId()) {
1956 continue;
1957 }
1958
Eric Laurent74708e72017-04-07 17:13:42 -07001959 audio_source_t activeSource = activeDesc->inputSource(true);
1960 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1961 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1962 if (activeDesc->hasPreemptedSession(session)) {
1963 ALOGW("startInput(%d) failed for HOTWORD: "
1964 "other input %d already started for HOTWORD",
1965 input, activeDesc->mIoHandle);
1966 return INVALID_OPERATION;
1967 }
1968 } else {
1969 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1970 input, activeDesc->mIoHandle);
1971 return INVALID_OPERATION;
1972 }
1973 } else {
1974 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1975 ALOGW("startInput(%d) failed: other input %d already started",
1976 input, activeDesc->mIoHandle);
1977 return INVALID_OPERATION;
1978 }
1979 }
1980 }
1981
Chris Thornton2b864642017-06-27 21:26:07 -07001982 // We only need to check if the sound trigger session supports concurrent capture if the
1983 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1984 // that's running.
1985 const bool allowConcurrentWithSoundTrigger =
1986 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1987
Eric Laurent74708e72017-04-07 17:13:42 -07001988 // if capture is allowed, preempt currently active HOTWORD captures
1989 for (size_t i = 0; i < activeInputs.size(); i++) {
1990 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1991
1992 if (is_virtual_input_device(activeDesc->mDevice)) {
1993 continue;
1994 }
1995
Chris Thornton2b864642017-06-27 21:26:07 -07001996 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1997 continue;
1998 }
1999
Eric Laurent74708e72017-04-07 17:13:42 -07002000 audio_source_t activeSource = activeDesc->inputSource(true);
2001 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2002 AudioSessionCollection activeSessions =
2003 activeDesc->getAudioSessions(true /*activeOnly*/);
2004 audio_session_t activeSession = activeSessions.keyAt(0);
2005 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2006 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
2007 sessions.add(activeSession);
2008 inputDesc->setPreemptedSessions(sessions);
2009 stopInput(activeHandle, activeSession);
2010 releaseInput(activeHandle, activeSession);
2011 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2012 input, activeDesc->mIoHandle);
2013 }
2014 }
2015 }
2016#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002017
Eric Laurent313d1e72016-01-29 09:56:57 -08002018 // increment activity count before calling getNewInputDevice() below as only active sessions
2019 // are considered for device selection
2020 audioSession->changeActiveCount(1);
2021
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002022 // Routing?
2023 mInputRoutes.incRouteActivity(session);
2024
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002025 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002026 // indicate active capture to sound trigger service if starting capture from a mic on
2027 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002028 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002029 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002030
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002031 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2032 // if input maps to a dynamic policy with an activity listener, notify of state change
2033 if ((inputDesc->mPolicyMix != NULL)
2034 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2035 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2036 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002037 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002038
Eric Laurentf7c50102016-09-30 15:19:43 -07002039 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2040 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002041 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002042 SoundTrigger::setCaptureState(true);
2043 }
2044
2045 // automatically enable the remote submix output when input is started if not
2046 // used by a policy mix of type MIX_TYPE_RECORDERS
2047 // For remote submix (a virtual device), we open only one input per capture request.
2048 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2049 String8 address = String8("");
2050 if (inputDesc->mPolicyMix == NULL) {
2051 address = String8("0");
2052 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2053 address = inputDesc->mPolicyMix->mDeviceAddress;
2054 }
2055 if (address != "") {
2056 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2057 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2058 address, "remote-submix");
2059 }
Eric Laurentc722f302014-12-10 11:21:49 -08002060 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002061 }
Eric Laurente552edb2014-03-10 17:42:56 -07002062 }
2063
Eric Laurent599c7582015-12-07 18:05:55 -08002064 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002065
Eric Laurente552edb2014-03-10 17:42:56 -07002066 return NO_ERROR;
2067}
2068
Eric Laurent4dc68062014-07-28 17:26:49 -07002069status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2070 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002071{
2072 ALOGV("stopInput() input %d", input);
2073 ssize_t index = mInputs.indexOfKey(input);
2074 if (index < 0) {
2075 ALOGW("stopInput() unknown input %d", input);
2076 return BAD_VALUE;
2077 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002078 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002079
Eric Laurent599c7582015-12-07 18:05:55 -08002080 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002081 if (index < 0) {
2082 ALOGW("stopInput() unknown session %d on input %d", session, input);
2083 return BAD_VALUE;
2084 }
2085
Eric Laurent599c7582015-12-07 18:05:55 -08002086 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002087 ALOGW("stopInput() input %d already stopped", input);
2088 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002089 }
2090
Eric Laurent599c7582015-12-07 18:05:55 -08002091 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002092
2093 // Routing?
2094 mInputRoutes.decRouteActivity(session);
2095
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002096 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002097
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002098 if (inputDesc->isActive()) {
2099 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2100 } else {
2101 // if input maps to a dynamic policy with an activity listener, notify of state change
2102 if ((inputDesc->mPolicyMix != NULL)
2103 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2104 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2105 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002106 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002107
2108 // automatically disable the remote submix output when input is stopped if not
2109 // used by a policy mix of type MIX_TYPE_RECORDERS
2110 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2111 String8 address = String8("");
2112 if (inputDesc->mPolicyMix == NULL) {
2113 address = String8("0");
2114 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2115 address = inputDesc->mPolicyMix->mDeviceAddress;
2116 }
2117 if (address != "") {
2118 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2119 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2120 address, "remote-submix");
2121 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002122 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002123
Eric Laurentf7c50102016-09-30 15:19:43 -07002124 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002125 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002126
Eric Laurentf7c50102016-09-30 15:19:43 -07002127 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2128 // primary HW module
2129 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2130 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2131 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002132 SoundTrigger::setCaptureState(false);
2133 }
2134 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002135 }
Eric Laurente552edb2014-03-10 17:42:56 -07002136 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002137 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002138}
2139
Eric Laurent4dc68062014-07-28 17:26:49 -07002140void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2141 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002142{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002143
Eric Laurente552edb2014-03-10 17:42:56 -07002144 ALOGV("releaseInput() %d", input);
2145 ssize_t index = mInputs.indexOfKey(input);
2146 if (index < 0) {
2147 ALOGW("releaseInput() releasing unknown input %d", input);
2148 return;
2149 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002150
2151 // Routing
2152 mInputRoutes.removeRoute(session);
2153
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002154 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2155 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002156
Eric Laurent599c7582015-12-07 18:05:55 -08002157 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002158 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002159 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2160 return;
2161 }
Eric Laurent599c7582015-12-07 18:05:55 -08002162
2163 if (audioSession->openCount() == 0) {
2164 ALOGW("releaseInput() invalid open count %d on session %d",
2165 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002166 return;
2167 }
Eric Laurent599c7582015-12-07 18:05:55 -08002168
2169 if (audioSession->changeOpenCount(-1) == 0) {
2170 inputDesc->removeAudioSession(session);
2171 }
2172
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002173 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002174 ALOGV("releaseInput() exit > 0");
2175 return;
2176 }
2177
Eric Laurent05b90f82014-08-27 15:32:29 -07002178 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002179 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002180 ALOGV("releaseInput() exit");
2181}
2182
Eric Laurentd4692962014-05-05 18:13:44 -07002183void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002184 bool patchRemoved = false;
2185
Eric Laurentd4692962014-05-05 18:13:44 -07002186 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002187 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002188 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002189 if (patch_index >= 0) {
2190 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002191 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002192 mAudioPatches.removeItemsAt(patch_index);
2193 patchRemoved = true;
2194 }
Eric Laurentd4692962014-05-05 18:13:44 -07002195 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2196 }
2197 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002198 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002199 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002200
2201 if (patchRemoved) {
2202 mpClientInterface->onAudioPatchListUpdate();
2203 }
Eric Laurentd4692962014-05-05 18:13:44 -07002204}
2205
Eric Laurente0720872014-03-11 09:30:41 -07002206void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002207 int indexMin,
2208 int indexMax)
2209{
2210 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002211 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002212
2213 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002214 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2215 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002216 continue;
2217 }
2218 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002219 }
Eric Laurente552edb2014-03-10 17:42:56 -07002220}
2221
Eric Laurente0720872014-03-11 09:30:41 -07002222status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002223 int index,
2224 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002225{
2226
François Gaffied1ab2bd2015-12-02 18:20:06 +01002227 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2228 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002229 return BAD_VALUE;
2230 }
2231 if (!audio_is_output_device(device)) {
2232 return BAD_VALUE;
2233 }
2234
2235 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002236 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002237
Eric Laurent1fd372e2016-04-06 14:23:53 -07002238 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002239 stream, device, index);
2240
Eric Laurent28d09f02016-03-08 10:43:05 -08002241 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002242 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2243 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002244 continue;
2245 }
2246 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2247 }
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Eric Laurent1fd372e2016-04-06 14:23:53 -07002249 // update volume on all outputs and streams matching the following:
2250 // - The requested stream (or a stream matching for volume control) is active on the output
2251 // - The device (or devices) selected by the strategy corresponding to this stream includes
2252 // the requested device
2253 // - For non default requested device, currently selected device on the output is either the
2254 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002255 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2256 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002257 status_t status = NO_ERROR;
2258 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002259 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2260 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002261 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2262 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002263 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002264 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002265 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2266 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002267 continue;
2268 }
Eric Laurent794fde22016-03-11 09:50:45 -08002269 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002270 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2271 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002272 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2273 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002274 continue;
2275 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002276 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002277 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002278 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002279 applyVolume = (curDevice & curStreamDevice) != 0;
2280 } else {
2281 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002282 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002283 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002284
Eric Laurente76f29c2016-09-14 17:17:53 -07002285 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002286 //FIXME: workaround for truncated touch sounds
2287 // delayed volume change for system stream to be removed when the problem is
2288 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002289 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002290 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2291 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002292 if (volStatus != NO_ERROR) {
2293 status = volStatus;
2294 }
2295 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002296 }
Eric Laurente552edb2014-03-10 17:42:56 -07002297 }
2298 return status;
2299}
2300
Eric Laurente0720872014-03-11 09:30:41 -07002301status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002302 int *index,
2303 audio_devices_t device)
2304{
2305 if (index == NULL) {
2306 return BAD_VALUE;
2307 }
2308 if (!audio_is_output_device(device)) {
2309 return BAD_VALUE;
2310 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002311 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002312 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002313 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002314 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2315 }
François Gaffiedfd74092015-03-19 12:10:59 +01002316 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002317
François Gaffied1ab2bd2015-12-02 18:20:06 +01002318 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002319 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2320 return NO_ERROR;
2321}
2322
Eric Laurent36829f92017-04-07 19:04:42 -07002323audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002324{
2325 // select one output among several suitable for global effects.
2326 // The priority is as follows:
2327 // 1: An offloaded output. If the effect ends up not being offloadable,
2328 // AudioFlinger will invalidate the track and the offloaded output
2329 // will be closed causing the effect to be moved to a PCM output.
2330 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002331 // 3: The primary output
2332 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002333
Eric Laurent3b73df72014-03-11 09:06:29 -07002334 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002335 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002336 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002337
Eric Laurent36829f92017-04-07 19:04:42 -07002338 if (outputs.size() == 0) {
2339 return AUDIO_IO_HANDLE_NONE;
2340 }
Eric Laurente552edb2014-03-10 17:42:56 -07002341
Eric Laurent36829f92017-04-07 19:04:42 -07002342 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2343 bool activeOnly = true;
2344
2345 while (output == AUDIO_IO_HANDLE_NONE) {
2346 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2347 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2348 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2349
2350 for (size_t i = 0; i < outputs.size(); i++) {
2351 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2352 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2353 continue;
2354 }
2355 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2356 activeOnly, i, desc->mFlags);
2357 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2358 outputOffloaded = outputs[i];
2359 }
2360 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2361 outputDeepBuffer = outputs[i];
2362 }
2363 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2364 outputPrimary = outputs[i];
2365 }
2366 }
2367 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2368 output = outputOffloaded;
2369 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2370 output = outputDeepBuffer;
2371 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2372 output = outputPrimary;
2373 } else {
2374 output = outputs[0];
2375 }
2376 activeOnly = false;
2377 }
2378
2379 if (output != mMusicEffectOutput) {
2380 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2381 mMusicEffectOutput = output;
2382 }
2383
2384 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002385 return output;
2386}
2387
Eric Laurent36829f92017-04-07 19:04:42 -07002388audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2389{
2390 return selectOutputForMusicEffects();
2391}
2392
Eric Laurente0720872014-03-11 09:30:41 -07002393status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002394 audio_io_handle_t io,
2395 uint32_t strategy,
2396 int session,
2397 int id)
2398{
2399 ssize_t index = mOutputs.indexOfKey(io);
2400 if (index < 0) {
2401 index = mInputs.indexOfKey(io);
2402 if (index < 0) {
2403 ALOGW("registerEffect() unknown io %d", io);
2404 return INVALID_OPERATION;
2405 }
2406 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002407 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002408}
2409
Eric Laurentc75307b2015-03-17 15:29:32 -07002410bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2411{
Eric Laurent28d09f02016-03-08 10:43:05 -08002412 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002413 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2414 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002415 continue;
2416 }
2417 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2418 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002419 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002420}
2421
2422bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2423{
2424 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2425}
2426
Eric Laurente0720872014-03-11 09:30:41 -07002427bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002428{
2429 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002430 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002431 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002432 return true;
2433 }
2434 }
2435 return false;
2436}
2437
Eric Laurent275e8e92014-11-30 15:14:47 -08002438// Register a list of custom mixes with their attributes and format.
2439// When a mix is registered, corresponding input and output profiles are
2440// added to the remote submix hw module. The profile contains only the
2441// parameters (sampling rate, format...) specified by the mix.
2442// The corresponding input remote submix device is also connected.
2443//
2444// When a remote submix device is connected, the address is checked to select the
2445// appropriate profile and the corresponding input or output stream is opened.
2446//
2447// When capture starts, getInputForAttr() will:
2448// - 1 look for a mix matching the address passed in attribtutes tags if any
2449// - 2 if none found, getDeviceForInputSource() will:
2450// - 2.1 look for a mix matching the attributes source
2451// - 2.2 if none found, default to device selection by policy rules
2452// At this time, the corresponding output remote submix device is also connected
2453// and active playback use cases can be transferred to this mix if needed when reconnecting
2454// after AudioTracks are invalidated
2455//
2456// When playback starts, getOutputForAttr() will:
2457// - 1 look for a mix matching the address passed in attribtutes tags if any
2458// - 2 if none found, look for a mix matching the attributes usage
2459// - 3 if none found, default to device and output selection by policy rules.
2460
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002461status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002462{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002463 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2464 status_t res = NO_ERROR;
2465
2466 sp<HwModule> rSubmixModule;
2467 // examine each mix's route type
2468 for (size_t i = 0; i < mixes.size(); i++) {
2469 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2470 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2471 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002472 break;
2473 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2475 // Loop back through "remote submix"
2476 if (rSubmixModule == 0) {
2477 for (size_t j = 0; i < mHwModules.size(); j++) {
2478 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2479 && mHwModules[j]->mHandle != 0) {
2480 rSubmixModule = mHwModules[j];
2481 break;
2482 }
2483 }
2484 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002485
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002487
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002488 if (rSubmixModule == 0) {
2489 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2490 res = INVALID_OPERATION;
2491 break;
2492 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002493
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002495
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002496 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002497 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002498 res = INVALID_OPERATION;
2499 break;
2500 }
2501 audio_config_t outputConfig = mixes[i].mFormat;
2502 audio_config_t inputConfig = mixes[i].mFormat;
2503 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2504 // stereo and let audio flinger do the channel conversion if needed.
2505 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2506 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2507 rSubmixModule->addOutputProfile(address, &outputConfig,
2508 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2509 rSubmixModule->addInputProfile(address, &inputConfig,
2510 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002511
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2513 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2514 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2515 address.string(), "remote-submix");
2516 } else {
2517 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2519 address.string(), "remote-submix");
2520 }
2521 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002524 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2525 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2529 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2530 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2531 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2532 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2533 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002534 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2535 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2537 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002538 } else {
2539 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 }
2541 break;
2542 }
2543 }
2544
2545 if (res != NO_ERROR) {
2546 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002547 i, device, address.string());
2548 res = INVALID_OPERATION;
2549 break;
2550 } else if (!foundOutput) {
2551 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2552 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 res = INVALID_OPERATION;
2554 break;
2555 }
Eric Laurentc722f302014-12-10 11:21:49 -08002556 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002557 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 if (res != NO_ERROR) {
2559 unregisterPolicyMixes(mixes);
2560 }
2561 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002562}
2563
2564status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2565{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002566 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002567 status_t res = NO_ERROR;
2568 sp<HwModule> rSubmixModule;
2569 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002570 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002571 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002572
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 if (rSubmixModule == 0) {
2574 for (size_t j = 0; i < mHwModules.size(); j++) {
2575 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2576 && mHwModules[j]->mHandle != 0) {
2577 rSubmixModule = mHwModules[j];
2578 break;
2579 }
2580 }
2581 }
2582 if (rSubmixModule == 0) {
2583 res = INVALID_OPERATION;
2584 continue;
2585 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002586
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002588
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2590 res = INVALID_OPERATION;
2591 continue;
2592 }
2593
2594 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2596 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2597 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2598 address.string(), "remote-submix");
2599 }
2600 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2601 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2602 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2604 address.string(), "remote-submix");
2605 }
2606 rSubmixModule->removeOutputProfile(address);
2607 rSubmixModule->removeInputProfile(address);
2608
2609 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2610 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2611 res = INVALID_OPERATION;
2612 continue;
2613 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002614 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002615 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002616 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002617}
2618
Eric Laurente552edb2014-03-10 17:42:56 -07002619
Eric Laurente0720872014-03-11 09:30:41 -07002620status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002621{
2622 const size_t SIZE = 256;
2623 char buffer[SIZE];
2624 String8 result;
2625
2626 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2627 result.append(buffer);
2628
Eric Laurent87ffa392015-05-22 10:32:38 -07002629 snprintf(buffer, SIZE, " Primary Output: %d\n",
2630 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002631 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002632 std::string stateLiteral;
2633 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2634 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002635 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002636 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002637 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002638 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002639 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002640 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002641 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002642 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002643 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002644 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002645 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002646 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002647 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002648 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002649 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002650 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2651 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2652 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002653 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2654 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002655 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2656 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002657
François Gaffie2110e042015-03-24 08:41:51 +01002658 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002659
François Gaffie112b0af2015-11-19 16:13:25 +01002660 mAvailableOutputDevices.dump(fd, String8("Available output"));
2661 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002662 mHwModules.dump(fd);
2663 mOutputs.dump(fd);
2664 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002665 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002666 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002667 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002668 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002669
2670 return NO_ERROR;
2671}
2672
2673// This function checks for the parameters which can be offloaded.
2674// This can be enhanced depending on the capability of the DSP and policy
2675// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002676bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002677{
2678 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002679 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002680 offloadInfo.sample_rate, offloadInfo.channel_mask,
2681 offloadInfo.format,
2682 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2683 offloadInfo.has_video);
2684
Andy Hung2ddee192015-12-18 17:34:44 -08002685 if (mMasterMono) {
2686 return false; // no offloading if mono is set.
2687 }
2688
Eric Laurente552edb2014-03-10 17:42:56 -07002689 // Check if offload has been disabled
2690 char propValue[PROPERTY_VALUE_MAX];
2691 if (property_get("audio.offload.disable", propValue, "0")) {
2692 if (atoi(propValue) != 0) {
2693 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2694 return false;
2695 }
2696 }
2697
2698 // Check if stream type is music, then only allow offload as of now.
2699 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2700 {
2701 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2702 return false;
2703 }
2704
2705 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002706 const bool allowOffloadWithVideo =
2707 property_get_bool("audio.offload.video", false /* default_value */);
2708 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002709 ALOGV("isOffloadSupported: has_video == true, returning false");
2710 return false;
2711 }
2712
2713 //If duration is less than minimum value defined in property, return false
2714 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2715 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2716 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2717 return false;
2718 }
2719 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2720 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2721 return false;
2722 }
2723
2724 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2725 // creating an offloaded track and tearing it down immediately after start when audioflinger
2726 // detects there is an active non offloadable effect.
2727 // FIXME: We should check the audio session here but we do not have it in this context.
2728 // This may prevent offloading in rare situations where effects are left active by apps
2729 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002730 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002731 return false;
2732 }
2733
2734 // See if there is a profile to support this.
2735 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002736 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002737 offloadInfo.sample_rate,
2738 offloadInfo.format,
2739 offloadInfo.channel_mask,
2740 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002741 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2742 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002743}
2744
Eric Laurent6a94d692014-05-20 11:18:06 -07002745status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2746 audio_port_type_t type,
2747 unsigned int *num_ports,
2748 struct audio_port *ports,
2749 unsigned int *generation)
2750{
2751 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2752 generation == NULL) {
2753 return BAD_VALUE;
2754 }
2755 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2756 if (ports == NULL) {
2757 *num_ports = 0;
2758 }
2759
2760 size_t portsWritten = 0;
2761 size_t portsMax = *num_ports;
2762 *num_ports = 0;
2763 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002764 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2765 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002766 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002767 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2768 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2769 continue;
2770 }
2771 if (portsWritten < portsMax) {
2772 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2773 }
2774 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002775 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002776 }
2777 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002778 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2779 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2780 continue;
2781 }
2782 if (portsWritten < portsMax) {
2783 mAvailableInputDevices[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 }
2789 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2790 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2791 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2792 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2793 }
2794 *num_ports += mInputs.size();
2795 }
2796 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002797 size_t numOutputs = 0;
2798 for (size_t i = 0; i < mOutputs.size(); i++) {
2799 if (!mOutputs[i]->isDuplicated()) {
2800 numOutputs++;
2801 if (portsWritten < portsMax) {
2802 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2803 }
2804 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002805 }
Eric Laurent84c70242014-06-23 08:46:27 -07002806 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002807 }
2808 }
2809 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002810 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002811 return NO_ERROR;
2812}
2813
2814status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2815{
2816 return NO_ERROR;
2817}
2818
Eric Laurent6a94d692014-05-20 11:18:06 -07002819status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2820 audio_patch_handle_t *handle,
2821 uid_t uid)
2822{
2823 ALOGV("createAudioPatch()");
2824
2825 if (handle == NULL || patch == NULL) {
2826 return BAD_VALUE;
2827 }
2828 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2829
Eric Laurent874c42872014-08-08 15:13:39 -07002830 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2831 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2832 return BAD_VALUE;
2833 }
2834 // only one source per audio patch supported for now
2835 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 return INVALID_OPERATION;
2837 }
Eric Laurent874c42872014-08-08 15:13:39 -07002838
2839 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002840 return INVALID_OPERATION;
2841 }
Eric Laurent874c42872014-08-08 15:13:39 -07002842 for (size_t i = 0; i < patch->num_sinks; i++) {
2843 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2844 return INVALID_OPERATION;
2845 }
2846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002847
2848 sp<AudioPatch> patchDesc;
2849 ssize_t index = mAudioPatches.indexOfKey(*handle);
2850
Eric Laurent6a94d692014-05-20 11:18:06 -07002851 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2852 patch->sources[0].role,
2853 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002854#if LOG_NDEBUG == 0
2855 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002856 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002857 patch->sinks[i].role,
2858 patch->sinks[i].type);
2859 }
2860#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002861
2862 if (index >= 0) {
2863 patchDesc = mAudioPatches.valueAt(index);
2864 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2865 mUidCached, patchDesc->mUid, uid);
2866 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2867 return INVALID_OPERATION;
2868 }
2869 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002870 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002871 }
2872
2873 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002874 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002875 if (outputDesc == NULL) {
2876 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2877 return BAD_VALUE;
2878 }
Eric Laurent84c70242014-06-23 08:46:27 -07002879 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2880 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 if (patchDesc != 0) {
2882 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2883 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2884 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2885 return BAD_VALUE;
2886 }
2887 }
Eric Laurent874c42872014-08-08 15:13:39 -07002888 DeviceVector devices;
2889 for (size_t i = 0; i < patch->num_sinks; i++) {
2890 // Only support mix to devices connection
2891 // TODO add support for mix to mix connection
2892 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2893 ALOGV("createAudioPatch() source mix but sink is not a device");
2894 return INVALID_OPERATION;
2895 }
2896 sp<DeviceDescriptor> devDesc =
2897 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2898 if (devDesc == 0) {
2899 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2900 return BAD_VALUE;
2901 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002902
François Gaffie53615e22015-03-19 09:24:12 +01002903 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002904 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002905 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002906 NULL, // updatedSamplingRate
2907 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002908 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002909 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002910 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002911 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002912 ALOGV("createAudioPatch() profile not supported for device %08x",
2913 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002914 return INVALID_OPERATION;
2915 }
2916 devices.add(devDesc);
2917 }
2918 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 return INVALID_OPERATION;
2920 }
Eric Laurent874c42872014-08-08 15:13:39 -07002921
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 // TODO: reconfigure output format and channels here
2923 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002924 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002925 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002926 index = mAudioPatches.indexOfKey(*handle);
2927 if (index >= 0) {
2928 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2929 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2930 }
2931 patchDesc = mAudioPatches.valueAt(index);
2932 patchDesc->mUid = uid;
2933 ALOGV("createAudioPatch() success");
2934 } else {
2935 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2936 return INVALID_OPERATION;
2937 }
2938 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2939 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2940 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002941 // only one sink supported when connecting an input device to a mix
2942 if (patch->num_sinks > 1) {
2943 return INVALID_OPERATION;
2944 }
François Gaffie53615e22015-03-19 09:24:12 +01002945 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002946 if (inputDesc == NULL) {
2947 return BAD_VALUE;
2948 }
2949 if (patchDesc != 0) {
2950 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2951 return BAD_VALUE;
2952 }
2953 }
2954 sp<DeviceDescriptor> devDesc =
2955 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2956 if (devDesc == 0) {
2957 return BAD_VALUE;
2958 }
2959
François Gaffie53615e22015-03-19 09:24:12 +01002960 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002961 devDesc->mAddress,
2962 patch->sinks[0].sample_rate,
2963 NULL, /*updatedSampleRate*/
2964 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002965 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002966 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002967 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002968 // FIXME for the parameter type,
2969 // and the NONE
2970 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002971 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002972 return INVALID_OPERATION;
2973 }
2974 // TODO: reconfigure output format and channels here
2975 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002976 devDesc->type(), inputDesc->mIoHandle);
2977 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002978 index = mAudioPatches.indexOfKey(*handle);
2979 if (index >= 0) {
2980 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2981 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2982 }
2983 patchDesc = mAudioPatches.valueAt(index);
2984 patchDesc->mUid = uid;
2985 ALOGV("createAudioPatch() success");
2986 } else {
2987 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2988 return INVALID_OPERATION;
2989 }
2990 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2991 // device to device connection
2992 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002993 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002994 return BAD_VALUE;
2995 }
2996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 sp<DeviceDescriptor> srcDeviceDesc =
2998 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002999 if (srcDeviceDesc == 0) {
3000 return BAD_VALUE;
3001 }
Eric Laurent874c42872014-08-08 15:13:39 -07003002
Eric Laurent6a94d692014-05-20 11:18:06 -07003003 //update source and sink with our own data as the data passed in the patch may
3004 // be incomplete.
3005 struct audio_patch newPatch = *patch;
3006 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007
Eric Laurent874c42872014-08-08 15:13:39 -07003008 for (size_t i = 0; i < patch->num_sinks; i++) {
3009 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3010 ALOGV("createAudioPatch() source device but one sink is not a device");
3011 return INVALID_OPERATION;
3012 }
3013
3014 sp<DeviceDescriptor> sinkDeviceDesc =
3015 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3016 if (sinkDeviceDesc == 0) {
3017 return BAD_VALUE;
3018 }
3019 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3020
Eric Laurent3bcf8592015-04-03 12:13:24 -07003021 // create a software bridge in PatchPanel if:
3022 // - source and sink devices are on differnt HW modules OR
3023 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003024 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003025 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003026 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003027 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003028 return INVALID_OPERATION;
3029 }
Eric Laurent874c42872014-08-08 15:13:39 -07003030 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003031 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003032 // if the sink device is reachable via an opened output stream, request to go via
3033 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003034 audio_io_handle_t output = selectOutput(outputs,
3035 AUDIO_OUTPUT_FLAG_NONE,
3036 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003037 if (output != AUDIO_IO_HANDLE_NONE) {
3038 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3039 if (outputDesc->isDuplicated()) {
3040 return INVALID_OPERATION;
3041 }
3042 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003043 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003044 newPatch.num_sources = 2;
3045 }
Eric Laurent83b88082014-06-20 18:31:16 -07003046 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003047 }
3048 // TODO: check from routing capabilities in config file and other conflicting patches
3049
3050 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3051 if (index >= 0) {
3052 afPatchHandle = patchDesc->mAfPatchHandle;
3053 }
3054
3055 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3056 &afPatchHandle,
3057 0);
3058 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3059 status, afPatchHandle);
3060 if (status == NO_ERROR) {
3061 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003062 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003063 addAudioPatch(patchDesc->mHandle, patchDesc);
3064 } else {
3065 patchDesc->mPatch = newPatch;
3066 }
3067 patchDesc->mAfPatchHandle = afPatchHandle;
3068 *handle = patchDesc->mHandle;
3069 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003070 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 } else {
3072 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3073 status);
3074 return INVALID_OPERATION;
3075 }
3076 } else {
3077 return BAD_VALUE;
3078 }
3079 } else {
3080 return BAD_VALUE;
3081 }
3082 return NO_ERROR;
3083}
3084
3085status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3086 uid_t uid)
3087{
3088 ALOGV("releaseAudioPatch() patch %d", handle);
3089
3090 ssize_t index = mAudioPatches.indexOfKey(handle);
3091
3092 if (index < 0) {
3093 return BAD_VALUE;
3094 }
3095 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3096 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3097 mUidCached, patchDesc->mUid, uid);
3098 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3099 return INVALID_OPERATION;
3100 }
3101
3102 struct audio_patch *patch = &patchDesc->mPatch;
3103 patchDesc->mUid = mUidCached;
3104 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003105 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003106 if (outputDesc == NULL) {
3107 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3108 return BAD_VALUE;
3109 }
3110
Eric Laurentc75307b2015-03-17 15:29:32 -07003111 setOutputDevice(outputDesc,
3112 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003113 true,
3114 0,
3115 NULL);
3116 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3117 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003118 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003119 if (inputDesc == NULL) {
3120 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3121 return BAD_VALUE;
3122 }
3123 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003124 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003125 true,
3126 NULL);
3127 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003128 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3129 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3130 status, patchDesc->mAfPatchHandle);
3131 removeAudioPatch(patchDesc->mHandle);
3132 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003133 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003134 } else {
3135 return BAD_VALUE;
3136 }
3137 } else {
3138 return BAD_VALUE;
3139 }
3140 return NO_ERROR;
3141}
3142
3143status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3144 struct audio_patch *patches,
3145 unsigned int *generation)
3146{
François Gaffie53615e22015-03-19 09:24:12 +01003147 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003148 return BAD_VALUE;
3149 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003150 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003151 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003152}
3153
Eric Laurente1715a42014-05-20 11:30:42 -07003154status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003155{
Eric Laurente1715a42014-05-20 11:30:42 -07003156 ALOGV("setAudioPortConfig()");
3157
3158 if (config == NULL) {
3159 return BAD_VALUE;
3160 }
3161 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3162 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003163 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3164 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003165 }
3166
Eric Laurenta121f902014-06-03 13:32:54 -07003167 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003168 if (config->type == AUDIO_PORT_TYPE_MIX) {
3169 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003170 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003171 if (outputDesc == NULL) {
3172 return BAD_VALUE;
3173 }
Eric Laurent84c70242014-06-23 08:46:27 -07003174 ALOG_ASSERT(!outputDesc->isDuplicated(),
3175 "setAudioPortConfig() called on duplicated output %d",
3176 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003177 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003178 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003179 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003180 if (inputDesc == NULL) {
3181 return BAD_VALUE;
3182 }
Eric Laurenta121f902014-06-03 13:32:54 -07003183 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003184 } else {
3185 return BAD_VALUE;
3186 }
3187 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3188 sp<DeviceDescriptor> deviceDesc;
3189 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3190 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3191 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3192 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3193 } else {
3194 return BAD_VALUE;
3195 }
3196 if (deviceDesc == NULL) {
3197 return BAD_VALUE;
3198 }
Eric Laurenta121f902014-06-03 13:32:54 -07003199 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003200 } else {
3201 return BAD_VALUE;
3202 }
3203
Eric Laurenta121f902014-06-03 13:32:54 -07003204 struct audio_port_config backupConfig;
3205 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3206 if (status == NO_ERROR) {
3207 struct audio_port_config newConfig;
3208 audioPortConfig->toAudioPortConfig(&newConfig, config);
3209 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003210 }
Eric Laurenta121f902014-06-03 13:32:54 -07003211 if (status != NO_ERROR) {
3212 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003213 }
Eric Laurente1715a42014-05-20 11:30:42 -07003214
3215 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003216}
3217
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003218void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3219{
Eric Laurentd60560a2015-04-10 11:31:20 -07003220 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003221 clearAudioPatches(uid);
3222 clearSessionRoutes(uid);
3223}
3224
Eric Laurent6a94d692014-05-20 11:18:06 -07003225void AudioPolicyManager::clearAudioPatches(uid_t uid)
3226{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003227 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003228 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3229 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003230 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003231 }
3232 }
3233}
3234
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003235void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3236 audio_io_handle_t ouptutToSkip)
3237{
3238 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3239 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3240 for (size_t j = 0; j < mOutputs.size(); j++) {
3241 if (mOutputs.keyAt(j) == ouptutToSkip) {
3242 continue;
3243 }
3244 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3245 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3246 continue;
3247 }
3248 // If the default device for this strategy is on another output mix,
3249 // invalidate all tracks in this strategy to force re connection.
3250 // Otherwise select new device on the output mix.
3251 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003252 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003253 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3254 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3255 }
3256 }
3257 } else {
3258 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3259 setOutputDevice(outputDesc, newDevice, false);
3260 }
3261 }
3262}
3263
3264void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3265{
3266 // remove output routes associated with this uid
3267 SortedVector<routing_strategy> affectedStrategies;
3268 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3269 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3270 if (route->mUid == uid) {
3271 mOutputRoutes.removeItemsAt(i);
3272 if (route->mDeviceDescriptor != 0) {
3273 affectedStrategies.add(getStrategy(route->mStreamType));
3274 }
3275 }
3276 }
3277 // reroute outputs if necessary
3278 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3279 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3280 }
3281
3282 // remove input routes associated with this uid
3283 SortedVector<audio_source_t> affectedSources;
3284 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3285 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3286 if (route->mUid == uid) {
3287 mInputRoutes.removeItemsAt(i);
3288 if (route->mDeviceDescriptor != 0) {
3289 affectedSources.add(route->mSource);
3290 }
3291 }
3292 }
3293 // reroute inputs if necessary
3294 SortedVector<audio_io_handle_t> inputsToClose;
3295 for (size_t i = 0; i < mInputs.size(); i++) {
3296 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003297 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003298 inputsToClose.add(inputDesc->mIoHandle);
3299 }
3300 }
3301 for (size_t i = 0; i < inputsToClose.size(); i++) {
3302 closeInput(inputsToClose[i]);
3303 }
3304}
3305
Eric Laurentd60560a2015-04-10 11:31:20 -07003306void AudioPolicyManager::clearAudioSources(uid_t uid)
3307{
3308 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3309 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3310 if (sourceDesc->mUid == uid) {
3311 stopAudioSource(mAudioSources.keyAt(i));
3312 }
3313 }
3314}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003315
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003316status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3317 audio_io_handle_t *ioHandle,
3318 audio_devices_t *device)
3319{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003320 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3321 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003322 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003323
François Gaffiedf372692015-03-19 10:43:27 +01003324 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003325}
3326
Eric Laurentd60560a2015-04-10 11:31:20 -07003327status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3328 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003329 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003330 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003331{
Eric Laurentd60560a2015-04-10 11:31:20 -07003332 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3333 if (source == NULL || attributes == NULL || handle == NULL) {
3334 return BAD_VALUE;
3335 }
3336
Glenn Kasten559d4392016-03-29 13:42:57 -07003337 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003338
3339 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3340 source->type != AUDIO_PORT_TYPE_DEVICE) {
3341 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3342 return INVALID_OPERATION;
3343 }
3344
3345 sp<DeviceDescriptor> srcDeviceDesc =
3346 mAvailableInputDevices.getDevice(source->ext.device.type,
3347 String8(source->ext.device.address));
3348 if (srcDeviceDesc == 0) {
3349 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3350 return BAD_VALUE;
3351 }
3352 sp<AudioSourceDescriptor> sourceDesc =
3353 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3354
3355 struct audio_patch dummyPatch;
3356 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3357 sourceDesc->mPatchDesc = patchDesc;
3358
3359 status_t status = connectAudioSource(sourceDesc);
3360 if (status == NO_ERROR) {
3361 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3362 *handle = sourceDesc->getHandle();
3363 }
3364 return status;
3365}
3366
3367status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3368{
3369 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3370
3371 // make sure we only have one patch per source.
3372 disconnectAudioSource(sourceDesc);
3373
3374 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003375 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003376 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3377
3378 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3379 sp<DeviceDescriptor> sinkDeviceDesc =
3380 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3381
3382 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3383 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3384
3385 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3386 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003387 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003388 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3389 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3390 // create patch between src device and output device
3391 // create Hwoutput and add to mHwOutputs
3392 } else {
3393 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3394 audio_io_handle_t output =
3395 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3396 if (output == AUDIO_IO_HANDLE_NONE) {
3397 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3398 return INVALID_OPERATION;
3399 }
3400 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3401 if (outputDesc->isDuplicated()) {
3402 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3403 return INVALID_OPERATION;
3404 }
3405 // create a special patch with no sink and two sources:
3406 // - the second source indicates to PatchPanel through which output mix this patch should
3407 // be connected as well as the stream type for volume control
3408 // - the sink is defined by whatever output device is currently selected for the output
3409 // though which this patch is routed.
3410 patch->num_sinks = 0;
3411 patch->num_sources = 2;
3412 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3413 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3414 patch->sources[1].ext.mix.usecase.stream = stream;
3415 status_t status = mpClientInterface->createAudioPatch(patch,
3416 &afPatchHandle,
3417 0);
3418 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3419 status, afPatchHandle);
3420 if (status != NO_ERROR) {
3421 ALOGW("%s patch panel could not connect device patch, error %d",
3422 __FUNCTION__, status);
3423 return INVALID_OPERATION;
3424 }
3425 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003426 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003427
3428 if (status != NO_ERROR) {
3429 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3430 return status;
3431 }
3432 sourceDesc->mSwOutput = outputDesc;
3433 if (delayMs != 0) {
3434 usleep(delayMs * 1000);
3435 }
3436 }
3437
3438 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3439 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3440
3441 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003442}
3443
Glenn Kasten559d4392016-03-29 13:42:57 -07003444status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003445{
Eric Laurentd60560a2015-04-10 11:31:20 -07003446 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3447 ALOGV("%s handle %d", __FUNCTION__, handle);
3448 if (sourceDesc == 0) {
3449 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3450 return BAD_VALUE;
3451 }
3452 status_t status = disconnectAudioSource(sourceDesc);
3453
3454 mAudioSources.removeItem(handle);
3455 return status;
3456}
3457
Andy Hung2ddee192015-12-18 17:34:44 -08003458status_t AudioPolicyManager::setMasterMono(bool mono)
3459{
3460 if (mMasterMono == mono) {
3461 return NO_ERROR;
3462 }
3463 mMasterMono = mono;
3464 // if enabling mono we close all offloaded devices, which will invalidate the
3465 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3466 // for recreating the new AudioTrack as non-offloaded PCM.
3467 //
3468 // If disabling mono, we leave all tracks as is: we don't know which clients
3469 // and tracks are able to be recreated as offloaded. The next "song" should
3470 // play back offloaded.
3471 if (mMasterMono) {
3472 Vector<audio_io_handle_t> offloaded;
3473 for (size_t i = 0; i < mOutputs.size(); ++i) {
3474 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3475 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3476 offloaded.push(desc->mIoHandle);
3477 }
3478 }
3479 for (size_t i = 0; i < offloaded.size(); ++i) {
3480 closeOutput(offloaded[i]);
3481 }
3482 }
3483 // update master mono for all remaining outputs
3484 for (size_t i = 0; i < mOutputs.size(); ++i) {
3485 updateMono(mOutputs.keyAt(i));
3486 }
3487 return NO_ERROR;
3488}
3489
3490status_t AudioPolicyManager::getMasterMono(bool *mono)
3491{
3492 *mono = mMasterMono;
3493 return NO_ERROR;
3494}
3495
Eric Laurentac9cef52017-06-09 15:46:26 -07003496float AudioPolicyManager::getStreamVolumeDB(
3497 audio_stream_type_t stream, int index, audio_devices_t device)
3498{
3499 return computeVolume(stream, index, device);
3500}
3501
Eric Laurentd60560a2015-04-10 11:31:20 -07003502status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3503{
3504 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3505
3506 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3507 if (patchDesc == 0) {
3508 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3509 sourceDesc->mPatchDesc->mHandle);
3510 return BAD_VALUE;
3511 }
3512 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3513
Eric Laurent28d09f02016-03-08 10:43:05 -08003514 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003515 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3516 if (swOutputDesc != 0) {
3517 stopSource(swOutputDesc, stream, false);
3518 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3519 } else {
3520 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3521 if (hwOutputDesc != 0) {
3522 // release patch between src device and output device
3523 // close Hwoutput and remove from mHwOutputs
3524 } else {
3525 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3526 }
3527 }
3528 return NO_ERROR;
3529}
3530
3531sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3532 audio_io_handle_t output, routing_strategy strategy)
3533{
3534 sp<AudioSourceDescriptor> source;
3535 for (size_t i = 0; i < mAudioSources.size(); i++) {
3536 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3537 routing_strategy sourceStrategy =
3538 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3539 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3540 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3541 source = sourceDesc;
3542 break;
3543 }
3544 }
3545 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003546}
3547
Eric Laurente552edb2014-03-10 17:42:56 -07003548// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003549// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003550// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003551uint32_t AudioPolicyManager::nextAudioPortGeneration()
3552{
3553 return android_atomic_inc(&mAudioPortGeneration);
3554}
3555
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003556#ifdef USE_XML_AUDIO_POLICY_CONF
3557// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3558static const char *kConfigLocationList[] =
3559 {"/odm/etc", "/vendor/etc", "/system/etc"};
3560static const int kConfigLocationListSize =
3561 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3562
3563static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3564 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3565 status_t ret;
3566
3567 for (int i = 0; i < kConfigLocationListSize; i++) {
3568 PolicySerializer serializer;
Aniket Kumar Lataadb11ed2018-01-31 20:26:59 -08003569 bool use_a2dp_offload_config =
3570 property_get_bool("persist.bluetooth.a2dp_offload.enable", false);
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003571 snprintf(audioPolicyXmlConfigFile,
3572 sizeof(audioPolicyXmlConfigFile),
3573 "%s/%s",
3574 kConfigLocationList[i],
Aniket Kumar Lataadb11ed2018-01-31 20:26:59 -08003575 use_a2dp_offload_config ? AUDIO_POLICY_A2DP_OFFLOAD_XML_CONFIG_FILE_NAME :
3576 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003577 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3578 if (ret == NO_ERROR) {
3579 break;
3580 }
3581 }
3582 return ret;
3583}
3584#endif
3585
Eric Laurente0720872014-03-11 09:30:41 -07003586AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003587 :
3588#ifdef AUDIO_POLICY_TEST
3589 Thread(false),
3590#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003591 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003592 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003593 mAudioPortGeneration(1),
3594 mBeaconMuteRefCount(0),
3595 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003596 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003597 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003598 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003599 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3600 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003601{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003602 mUidCached = getuid();
3603 mpClientInterface = clientInterface;
3604
3605 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3606 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3607 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3608 bool speakerDrcEnabled = false;
3609
3610#ifdef USE_XML_AUDIO_POLICY_CONF
3611 mVolumeCurves = new VolumeCurvesCollection();
3612 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3613 mDefaultOutputDevice, speakerDrcEnabled,
3614 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003615 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003616#else
3617 mVolumeCurves = new StreamDescriptorCollection();
3618 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3619 mDefaultOutputDevice, speakerDrcEnabled);
3620 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3621 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3622#endif
3623 ALOGE("could not load audio policy configuration file, setting defaults");
3624 config.setDefault();
3625 }
3626 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3627 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3628
3629 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003630 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3631 if (!engineInstance) {
3632 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3633 return;
3634 }
3635 // Retrieve the Policy Manager Interface
3636 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3637 if (mEngine == NULL) {
3638 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3639 return;
3640 }
3641 mEngine->setObserver(this);
3642 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003643 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003644 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3645
Eric Laurent3a4311c2014-03-17 12:00:47 -07003646 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003647 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003648 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3649 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003651 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003652 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003653 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003654 continue;
3655 }
3656 // open all output streams needed to access attached devices
3657 // except for direct output streams that are only opened when they are actually
3658 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003659 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003660 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3661 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003662 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003663
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003664 if (!outProfile->hasSupportedDevices()) {
3665 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003666 continue;
3667 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003668 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003669 mTtsOutputAvailable = true;
3670 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003671
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003672 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003673 continue;
3674 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003675 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003676 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3677 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003678 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003679 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003680 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003681 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003682 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003683 if ((profileType & outputDeviceTypes) == 0) {
3684 continue;
3685 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003686 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3687 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003688 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3689 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3690 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3691 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003692
3693 outputDesc->mDevice = profileType;
3694 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3695 config.sample_rate = outputDesc->mSamplingRate;
3696 config.channel_mask = outputDesc->mChannelMask;
3697 config.format = outputDesc->mFormat;
3698 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003699 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003700 &output,
3701 &config,
3702 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003703 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003704 &outputDesc->mLatency,
3705 outputDesc->mFlags);
3706
3707 if (status != NO_ERROR) {
3708 ALOGW("Cannot open output stream for device %08x on hw module %s",
3709 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003710 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003711 } else {
3712 outputDesc->mSamplingRate = config.sample_rate;
3713 outputDesc->mChannelMask = config.channel_mask;
3714 outputDesc->mFormat = config.format;
3715
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003716 for (size_t k = 0; k < supportedDevices.size(); k++) {
3717 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003718 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003719 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3720 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003721 }
3722 }
3723 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003724 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003725 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003726 }
3727 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003728 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003729 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003730 true,
3731 0,
3732 NULL,
3733 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003734 }
Eric Laurente552edb2014-03-10 17:42:56 -07003735 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003736 // open input streams needed to access attached devices to validate
3737 // mAvailableInputDevices list
3738 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3739 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003740 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003741
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003742 if (!inProfile->hasSupportedDevices()) {
3743 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003744 continue;
3745 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003746 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003747 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003748 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3749
Eric Laurentd78f1532014-09-16 16:38:20 -07003750 if ((profileType & inputDeviceTypes) == 0) {
3751 continue;
3752 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003753 sp<AudioInputDescriptor> inputDesc =
3754 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003755
Eric Laurentd78f1532014-09-16 16:38:20 -07003756 inputDesc->mDevice = profileType;
3757
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003758 // find the address
3759 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3760 // the inputs vector must be of size 1, but we don't want to crash here
3761 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3762 : String8("");
3763 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3764 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3765
Eric Laurentd78f1532014-09-16 16:38:20 -07003766 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3767 config.sample_rate = inputDesc->mSamplingRate;
3768 config.channel_mask = inputDesc->mChannelMask;
3769 config.format = inputDesc->mFormat;
3770 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003771 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003772 &input,
3773 &config,
3774 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003775 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003776 AUDIO_SOURCE_MIC,
3777 AUDIO_INPUT_FLAG_NONE);
3778
3779 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003780 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3781 for (size_t k = 0; k < supportedDevices.size(); k++) {
3782 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003783 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003784 if (index >= 0) {
3785 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3786 if (!devDesc->isAttached()) {
3787 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003788 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003789 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003790 }
3791 }
3792 mpClientInterface->closeInput(input);
3793 } else {
3794 ALOGW("Cannot open input stream for device %08x on hw module %s",
3795 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003796 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003797 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003798 }
3799 }
3800 // make sure all attached devices have been allocated a unique ID
3801 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003802 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003803 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003804 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3805 continue;
3806 }
François Gaffie2110e042015-03-24 08:41:51 +01003807 // The device is now validated and can be appended to the available devices of the engine
3808 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3809 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003810 i++;
3811 }
3812 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003813 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003814 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003815 mAvailableInputDevices.remove(mAvailableInputDevices[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(mAvailableInputDevices[i],
3820 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003821 i++;
3822 }
3823 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003824 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003825 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003826 }
Eric Laurente552edb2014-03-10 17:42:56 -07003827
3828 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3829
3830 updateDevicesAndOutputs();
3831
3832#ifdef AUDIO_POLICY_TEST
3833 if (mPrimaryOutput != 0) {
3834 AudioParameter outputCmd = AudioParameter();
3835 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003836 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003837
3838 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3839 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003840 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3841 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003842 mTestLatencyMs = 0;
3843 mCurOutput = 0;
3844 mDirectOutput = false;
3845 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3846 mTestOutputs[i] = 0;
3847 }
3848
3849 const size_t SIZE = 256;
3850 char buffer[SIZE];
3851 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3852 run(buffer, ANDROID_PRIORITY_AUDIO);
3853 }
3854#endif //AUDIO_POLICY_TEST
3855}
3856
Eric Laurente0720872014-03-11 09:30:41 -07003857AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003858{
3859#ifdef AUDIO_POLICY_TEST
3860 exit();
3861#endif //AUDIO_POLICY_TEST
3862 for (size_t i = 0; i < mOutputs.size(); i++) {
3863 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003864 }
3865 for (size_t i = 0; i < mInputs.size(); i++) {
3866 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003867 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003868 mAvailableOutputDevices.clear();
3869 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003870 mOutputs.clear();
3871 mInputs.clear();
3872 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003873}
3874
Eric Laurente0720872014-03-11 09:30:41 -07003875status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003876{
Eric Laurent87ffa392015-05-22 10:32:38 -07003877 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003878}
3879
3880#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003881bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003882{
3883 ALOGV("entering threadLoop()");
3884 while (!exitPending())
3885 {
3886 String8 command;
3887 int valueInt;
3888 String8 value;
3889
3890 Mutex::Autolock _l(mLock);
3891 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3892
3893 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3894 AudioParameter param = AudioParameter(command);
3895
3896 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3897 valueInt != 0) {
3898 ALOGV("Test command %s received", command.string());
3899 String8 target;
3900 if (param.get(String8("target"), target) != NO_ERROR) {
3901 target = "Manager";
3902 }
3903 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3904 param.remove(String8("test_cmd_policy_output"));
3905 mCurOutput = valueInt;
3906 }
3907 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3908 param.remove(String8("test_cmd_policy_direct"));
3909 if (value == "false") {
3910 mDirectOutput = false;
3911 } else if (value == "true") {
3912 mDirectOutput = true;
3913 }
3914 }
3915 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3916 param.remove(String8("test_cmd_policy_input"));
3917 mTestInput = valueInt;
3918 }
3919
3920 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3921 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003922 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003923 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003924 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003925 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003926 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003927 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003928 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003929 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003930 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003931 if (target == "Manager") {
3932 mTestFormat = format;
3933 } else if (mTestOutputs[mCurOutput] != 0) {
3934 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003935 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003936 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3937 }
3938 }
3939 }
3940 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3941 param.remove(String8("test_cmd_policy_channels"));
3942 int channels = 0;
3943
3944 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003945 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003946 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003947 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003948 }
3949 if (channels != 0) {
3950 if (target == "Manager") {
3951 mTestChannels = channels;
3952 } else if (mTestOutputs[mCurOutput] != 0) {
3953 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003954 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003955 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3956 }
3957 }
3958 }
3959 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3960 param.remove(String8("test_cmd_policy_sampleRate"));
3961 if (valueInt >= 0 && valueInt <= 96000) {
3962 int samplingRate = valueInt;
3963 if (target == "Manager") {
3964 mTestSamplingRate = samplingRate;
3965 } else if (mTestOutputs[mCurOutput] != 0) {
3966 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003967 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003968 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3969 }
3970 }
3971 }
3972
3973 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3974 param.remove(String8("test_cmd_policy_reopen"));
3975
Eric Laurentc75307b2015-03-17 15:29:32 -07003976 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003977
Eric Laurentc75307b2015-03-17 15:29:32 -07003978 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003979
Eric Laurentc75307b2015-03-17 15:29:32 -07003980 removeOutput(mPrimaryOutput->mIoHandle);
3981 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3982 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003983 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003984 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3985 config.sample_rate = outputDesc->mSamplingRate;
3986 config.channel_mask = outputDesc->mChannelMask;
3987 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003988 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003989 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003991 &config,
3992 &outputDesc->mDevice,
3993 String8(""),
3994 &outputDesc->mLatency,
3995 outputDesc->mFlags);
3996 if (status != NO_ERROR) {
3997 ALOGE("Failed to reopen hardware output stream, "
3998 "samplingRate: %d, format %d, channels %d",
3999 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07004000 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004001 outputDesc->mSamplingRate = config.sample_rate;
4002 outputDesc->mChannelMask = config.channel_mask;
4003 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07004004 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07004005 AudioParameter outputCmd = AudioParameter();
4006 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07004007 mpClientInterface->setParameters(handle, outputCmd.toString());
4008 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07004009 }
4010 }
4011
4012
4013 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
4014 }
4015 }
4016 return false;
4017}
4018
Eric Laurente0720872014-03-11 09:30:41 -07004019void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07004020{
4021 {
4022 AutoMutex _l(mLock);
4023 requestExit();
4024 mWaitWorkCV.signal();
4025 }
4026 requestExitAndWait();
4027}
4028
Eric Laurente0720872014-03-11 09:30:41 -07004029int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004030{
4031 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4032 if (output == mTestOutputs[i]) return i;
4033 }
4034 return 0;
4035}
4036#endif //AUDIO_POLICY_TEST
4037
4038// ---
4039
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004040void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004041{
François Gaffie98cc1912015-03-18 17:52:40 +01004042 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004043 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004044 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004045 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004046 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004047}
4048
François Gaffie53615e22015-03-19 09:24:12 +01004049void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4050{
4051 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004052 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004053}
4054
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004055void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004056{
François Gaffie98cc1912015-03-18 17:52:40 +01004057 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004058 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004059 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004060}
Eric Laurente552edb2014-03-10 17:42:56 -07004061
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004062void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004063 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004064 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004065 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004066 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004067 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004068 if (devDesc != 0) {
4069 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4070 desc->mIoHandle, address.string());
4071 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004072 }
4073}
4074
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004075status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004076 audio_policy_dev_state_t state,
4077 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004078 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004079{
François Gaffie53615e22015-03-19 09:24:12 +01004080 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004081 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004082
4083 if (audio_device_is_digital(device)) {
4084 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004085 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004086 }
Eric Laurente552edb2014-03-10 17:42:56 -07004087
Eric Laurent3b73df72014-03-11 09:06:29 -07004088 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004089 // first list already open outputs that can be routed to this device
4090 for (size_t i = 0; i < mOutputs.size(); i++) {
4091 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004092 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004093 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004094 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4095 outputs.add(mOutputs.keyAt(i));
4096 } else {
4097 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004098 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004099 }
Eric Laurente552edb2014-03-10 17:42:56 -07004100 }
4101 }
4102 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004103 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004104 for (size_t i = 0; i < mHwModules.size(); i++)
4105 {
4106 if (mHwModules[i]->mHandle == 0) {
4107 continue;
4108 }
4109 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4110 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004111 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004112 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004113 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004114 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004115 profiles.add(profile);
4116 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4117 }
Eric Laurente552edb2014-03-10 17:42:56 -07004118 }
4119 }
4120 }
4121
Eric Laurent7b279bb2015-12-14 10:18:23 -08004122 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004123
Eric Laurente552edb2014-03-10 17:42:56 -07004124 if (profiles.isEmpty() && outputs.isEmpty()) {
4125 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4126 return BAD_VALUE;
4127 }
4128
4129 // open outputs for matching profiles if needed. Direct outputs are also opened to
4130 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4131 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004132 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004133
4134 // nothing to do if one output is already opened for this profile
4135 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004136 for (j = 0; j < outputs.size(); j++) {
4137 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004138 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004139 // matching profile: save the sample rates, format and channel masks supported
4140 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004141 if (audio_device_is_digital(device)) {
4142 devDesc->importAudioPort(profile);
4143 }
Eric Laurente552edb2014-03-10 17:42:56 -07004144 break;
4145 }
4146 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004147 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004148 continue;
4149 }
4150
Eric Laurent83efe1c2017-07-09 16:51:08 -07004151 ALOGV("opening output for device %08x with params %s profile %p name %s",
4152 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004153 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004154 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004155 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4156 config.sample_rate = desc->mSamplingRate;
4157 config.channel_mask = desc->mChannelMask;
4158 config.format = desc->mFormat;
4159 config.offload_info.sample_rate = desc->mSamplingRate;
4160 config.offload_info.channel_mask = desc->mChannelMask;
4161 config.offload_info.format = desc->mFormat;
4162 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004163 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004164 &output,
4165 &config,
4166 &desc->mDevice,
4167 address,
4168 &desc->mLatency,
4169 desc->mFlags);
4170 if (status == NO_ERROR) {
4171 desc->mSamplingRate = config.sample_rate;
4172 desc->mChannelMask = config.channel_mask;
4173 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004174
Eric Laurentd4692962014-05-05 18:13:44 -07004175 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004176 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004177 char *param = audio_device_address_to_parameter(device, address);
4178 mpClientInterface->setParameters(output, String8(param));
4179 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004180 }
Phil Burk00eeb322016-03-31 12:41:00 -07004181 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004182 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004183 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004184 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004185 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004186 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004187 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004188 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004189 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004190 config.offload_info.sample_rate = config.sample_rate;
4191 config.offload_info.channel_mask = config.channel_mask;
4192 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004193 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004194 &output,
4195 &config,
4196 &desc->mDevice,
4197 address,
4198 &desc->mLatency,
4199 desc->mFlags);
4200 if (status == NO_ERROR) {
4201 desc->mSamplingRate = config.sample_rate;
4202 desc->mChannelMask = config.channel_mask;
4203 desc->mFormat = config.format;
4204 } else {
4205 output = AUDIO_IO_HANDLE_NONE;
4206 }
Eric Laurentd4692962014-05-05 18:13:44 -07004207 }
4208
Eric Laurentcf2c0212014-07-25 16:20:43 -07004209 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004211 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004212 sp<AudioPolicyMix> policyMix;
4213 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004214 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4215 address.string());
4216 }
François Gaffie036e1e92015-03-19 10:16:24 +01004217 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004218 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004219
Eric Laurent87ffa392015-05-22 10:32:38 -07004220 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4221 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004222 // no duplicated output for direct outputs and
4223 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004224 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004225
Eric Laurentd4692962014-05-05 18:13:44 -07004226 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004227 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004228
Eric Laurentd4692962014-05-05 18:13:44 -07004229 //TODO: configure audio effect output stage here
4230
4231 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004232 duplicatedOutput =
4233 mpClientInterface->openDuplicateOutput(output,
4234 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004235 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004236 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004237 sp<SwAudioOutputDescriptor> dupOutputDesc =
4238 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4239 dupOutputDesc->mOutput1 = mPrimaryOutput;
4240 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004241 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4242 dupOutputDesc->mFormat = desc->mFormat;
4243 dupOutputDesc->mChannelMask = desc->mChannelMask;
4244 dupOutputDesc->mLatency = desc->mLatency;
4245 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004246 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004247 } else {
4248 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004249 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004250 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004251 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004252 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004253 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004254 }
Eric Laurente552edb2014-03-10 17:42:56 -07004255 }
4256 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004257 } else {
4258 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004259 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004260 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004261 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004262 profiles.removeAt(profile_index);
4263 profile_index--;
4264 } else {
4265 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004266 // Load digital format info only for digital devices
4267 if (audio_device_is_digital(device)) {
4268 devDesc->importAudioPort(profile);
4269 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004270
François Gaffie53615e22015-03-19 09:24:12 +01004271 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004272 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4273 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004274 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004275 NULL/*patch handle*/, address.string());
4276 }
Eric Laurente552edb2014-03-10 17:42:56 -07004277 ALOGV("checkOutputsForDevice(): adding output %d", output);
4278 }
4279 }
4280
4281 if (profiles.isEmpty()) {
4282 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4283 return BAD_VALUE;
4284 }
Eric Laurentd4692962014-05-05 18:13:44 -07004285 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004286 // check if one opened output is not needed any more after disconnecting one device
4287 for (size_t i = 0; i < mOutputs.size(); i++) {
4288 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004289 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004290 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004291 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004292 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004293 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004294 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004295 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4296 mOutputs.keyAt(i));
4297 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004298 }
Eric Laurente552edb2014-03-10 17:42:56 -07004299 }
4300 }
Eric Laurentd4692962014-05-05 18:13:44 -07004301 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004302 for (size_t i = 0; i < mHwModules.size(); i++)
4303 {
4304 if (mHwModules[i]->mHandle == 0) {
4305 continue;
4306 }
4307 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4308 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004309 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004310 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004311 ALOGV("checkOutputsForDevice(): "
4312 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004313 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004314 }
4315 }
4316 }
4317 }
4318 return NO_ERROR;
4319}
4320
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004321status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004322 audio_policy_dev_state_t state,
4323 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004324 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004325{
Paul McLean9080a4c2015-06-18 08:24:02 -07004326 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004327 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004328
4329 if (audio_device_is_digital(device)) {
4330 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004331 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004332 }
4333
Eric Laurentd4692962014-05-05 18:13:44 -07004334 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4335 // first list already open inputs that can be routed to this device
4336 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4337 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004338 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004339 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4340 inputs.add(mInputs.keyAt(input_index));
4341 }
4342 }
4343
4344 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004345 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004346 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4347 {
4348 if (mHwModules[module_idx]->mHandle == 0) {
4349 continue;
4350 }
4351 for (size_t profile_index = 0;
4352 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4353 profile_index++)
4354 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004355 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4356
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004357 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004358 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004359 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004360 profiles.add(profile);
4361 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4362 profile_index, module_idx);
4363 }
Eric Laurentd4692962014-05-05 18:13:44 -07004364 }
4365 }
4366 }
4367
4368 if (profiles.isEmpty() && inputs.isEmpty()) {
4369 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4370 return BAD_VALUE;
4371 }
4372
4373 // open inputs for matching profiles if needed. Direct inputs are also opened to
4374 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4375 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4376
Eric Laurent1c333e22014-05-20 10:48:17 -07004377 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004378 // nothing to do if one input is already opened for this profile
4379 size_t input_index;
4380 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4381 desc = mInputs.valueAt(input_index);
4382 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004383 if (audio_device_is_digital(device)) {
4384 devDesc->importAudioPort(profile);
4385 }
Eric Laurentd4692962014-05-05 18:13:44 -07004386 break;
4387 }
4388 }
4389 if (input_index != mInputs.size()) {
4390 continue;
4391 }
4392
4393 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4394 desc = new AudioInputDescriptor(profile);
4395 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004396 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4397 config.sample_rate = desc->mSamplingRate;
4398 config.channel_mask = desc->mChannelMask;
4399 config.format = desc->mFormat;
4400 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004401
4402 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4403 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4404
Eric Laurent322b4d22015-04-03 15:57:54 -07004405 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004406 &input,
4407 &config,
4408 &desc->mDevice,
4409 address,
4410 AUDIO_SOURCE_MIC,
4411 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004412
Eric Laurentcf2c0212014-07-25 16:20:43 -07004413 if (status == NO_ERROR) {
4414 desc->mSamplingRate = config.sample_rate;
4415 desc->mChannelMask = config.channel_mask;
4416 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004417
Eric Laurentd4692962014-05-05 18:13:44 -07004418 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004419 char *param = audio_device_address_to_parameter(device, address);
4420 mpClientInterface->setParameters(input, String8(param));
4421 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004422 }
Phil Burk00eeb322016-03-31 12:41:00 -07004423 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004424 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004425 ALOGW("checkInputsForDevice() direct input missing param");
4426 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004427 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004428 }
4429
4430 if (input != 0) {
4431 addInput(input, desc);
4432 }
4433 } // endif input != 0
4434
Eric Laurentcf2c0212014-07-25 16:20:43 -07004435 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004436 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004437 profiles.removeAt(profile_index);
4438 profile_index--;
4439 } else {
4440 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004441 if (audio_device_is_digital(device)) {
4442 devDesc->importAudioPort(profile);
4443 }
Eric Laurentd4692962014-05-05 18:13:44 -07004444 ALOGV("checkInputsForDevice(): adding input %d", input);
4445 }
4446 } // end scan profiles
4447
4448 if (profiles.isEmpty()) {
4449 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4450 return BAD_VALUE;
4451 }
4452 } else {
4453 // Disconnect
4454 // check if one opened input is not needed any more after disconnecting one device
4455 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4456 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004457 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004458 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4459 mInputs.keyAt(input_index));
4460 inputs.add(mInputs.keyAt(input_index));
4461 }
4462 }
4463 // Clear any profiles associated with the disconnected device.
4464 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4465 if (mHwModules[module_index]->mHandle == 0) {
4466 continue;
4467 }
4468 for (size_t profile_index = 0;
4469 profile_index < mHwModules[module_index]->mInputProfiles.size();
4470 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004471 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004472 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004473 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004474 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004475 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004476 }
4477 }
4478 }
4479 } // end disconnect
4480
4481 return NO_ERROR;
4482}
4483
4484
Eric Laurente0720872014-03-11 09:30:41 -07004485void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004486{
4487 ALOGV("closeOutput(%d)", output);
4488
Eric Laurentc75307b2015-03-17 15:29:32 -07004489 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004490 if (outputDesc == NULL) {
4491 ALOGW("closeOutput() unknown output %d", output);
4492 return;
4493 }
François Gaffie036e1e92015-03-19 10:16:24 +01004494 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004495
Eric Laurente552edb2014-03-10 17:42:56 -07004496 // look for duplicated outputs connected to the output being removed.
4497 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004498 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004499 if (dupOutputDesc->isDuplicated() &&
4500 (dupOutputDesc->mOutput1 == outputDesc ||
4501 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004502 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004503 if (dupOutputDesc->mOutput1 == outputDesc) {
4504 outputDesc2 = dupOutputDesc->mOutput2;
4505 } else {
4506 outputDesc2 = dupOutputDesc->mOutput1;
4507 }
4508 // As all active tracks on duplicated output will be deleted,
4509 // and as they were also referenced on the other output, the reference
4510 // count for their stream type must be adjusted accordingly on
4511 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004512 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004513 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004514 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 }
4516 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4517 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4518
4519 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004520 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004521 }
4522 }
4523
Eric Laurent05b90f82014-08-27 15:32:29 -07004524 nextAudioPortGeneration();
4525
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004526 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004527 if (index >= 0) {
4528 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004529 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004530 mAudioPatches.removeItemsAt(index);
4531 mpClientInterface->onAudioPatchListUpdate();
4532 }
4533
Eric Laurente552edb2014-03-10 17:42:56 -07004534 AudioParameter param;
4535 param.add(String8("closing"), String8("true"));
4536 mpClientInterface->setParameters(output, param.toString());
4537
4538 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004539 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004541}
4542
4543void AudioPolicyManager::closeInput(audio_io_handle_t input)
4544{
4545 ALOGV("closeInput(%d)", input);
4546
4547 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4548 if (inputDesc == NULL) {
4549 ALOGW("closeInput() unknown input %d", input);
4550 return;
4551 }
4552
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004554
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004555 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004556 if (index >= 0) {
4557 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004558 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004559 mAudioPatches.removeItemsAt(index);
4560 mpClientInterface->onAudioPatchListUpdate();
4561 }
4562
4563 mpClientInterface->closeInput(input);
4564 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004565}
4566
Eric Laurentc75307b2015-03-17 15:29:32 -07004567SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4568 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004569 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004570{
4571 SortedVector<audio_io_handle_t> outputs;
4572
4573 ALOGVV("getOutputsForDevice() device %04x", device);
4574 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004575 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004576 i, openOutputs.valueAt(i)->isDuplicated(),
4577 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004578 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4579 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4580 outputs.add(openOutputs.keyAt(i));
4581 }
4582 }
4583 return outputs;
4584}
4585
Eric Laurente0720872014-03-11 09:30:41 -07004586bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004587 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004588{
4589 if (outputs1.size() != outputs2.size()) {
4590 return false;
4591 }
4592 for (size_t i = 0; i < outputs1.size(); i++) {
4593 if (outputs1[i] != outputs2[i]) {
4594 return false;
4595 }
4596 }
4597 return true;
4598}
4599
Eric Laurente0720872014-03-11 09:30:41 -07004600void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004601{
4602 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4603 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4604 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4605 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4606
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004607 // also take into account external policy-related changes: add all outputs which are
4608 // associated with policies in the "before" and "after" output vectors
4609 ALOGVV("checkOutputForStrategy(): policy related outputs");
4610 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004611 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004612 if (desc != 0 && desc->mPolicyMix != NULL) {
4613 srcOutputs.add(desc->mIoHandle);
4614 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4615 }
4616 }
4617 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004618 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004619 if (desc != 0 && desc->mPolicyMix != NULL) {
4620 dstOutputs.add(desc->mIoHandle);
4621 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4622 }
4623 }
4624
Eric Laurente552edb2014-03-10 17:42:56 -07004625 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4626 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4627 strategy, srcOutputs[0], dstOutputs[0]);
4628 // mute strategy while moving tracks from one output to another
4629 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004631 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004632 setStrategyMute(strategy, true, desc);
4633 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004634 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004635 sp<AudioSourceDescriptor> source =
4636 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4637 if (source != 0){
4638 connectAudioSource(source);
4639 }
Eric Laurente552edb2014-03-10 17:42:56 -07004640 }
4641
4642 // Move effects associated to this strategy from previous output to new output
4643 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004644 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004645 }
4646 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004647 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004648 if (getStrategy((audio_stream_type_t)i) == strategy) {
4649 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004650 }
4651 }
4652 }
4653}
4654
Eric Laurente0720872014-03-11 09:30:41 -07004655void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004656{
François Gaffie2110e042015-03-24 08:41:51 +01004657 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004658 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004659 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004660 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004661 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004662 checkOutputForStrategy(STRATEGY_SONIFICATION);
4663 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004664 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004665 checkOutputForStrategy(STRATEGY_MEDIA);
4666 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004667 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004668}
4669
Eric Laurente0720872014-03-11 09:30:41 -07004670void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004671{
François Gaffie53615e22015-03-19 09:24:12 +01004672 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lata32371762018-01-31 20:24:23 -08004673 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004674 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004675 return;
4676 }
4677
Eric Laurent3a4311c2014-03-17 12:00:47 -07004678 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004679 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4680 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4681 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004682
4683 // if suspended, restore A2DP output if:
4684 // ((SCO device is NOT connected) ||
4685 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4686 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004687 //
Eric Laurentf732e072016-08-03 19:30:28 -07004688 // if not suspended, suspend A2DP output if:
4689 // (SCO device is connected) &&
4690 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4691 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004692 //
4693 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004694 if (!isScoConnected ||
4695 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4696 AUDIO_POLICY_FORCE_BT_SCO) &&
4697 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4698 AUDIO_POLICY_FORCE_BT_SCO) &&
4699 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004700 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004701
4702 mpClientInterface->restoreOutput(a2dpOutput);
4703 mA2dpSuspended = false;
4704 }
4705 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004706 if (isScoConnected &&
4707 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4708 AUDIO_POLICY_FORCE_BT_SCO) ||
4709 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4710 AUDIO_POLICY_FORCE_BT_SCO) ||
4711 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004712 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004713
4714 mpClientInterface->suspendOutput(a2dpOutput);
4715 mA2dpSuspended = true;
4716 }
4717 }
4718}
4719
Eric Laurentc75307b2015-03-17 15:29:32 -07004720audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4721 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004722{
4723 audio_devices_t device = AUDIO_DEVICE_NONE;
4724
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004725 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 if (index >= 0) {
4727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4728 if (patchDesc->mUid != mUidCached) {
4729 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004730 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 return outputDesc->device();
4732 }
4733 }
4734
Eric Laurente552edb2014-03-10 17:42:56 -07004735 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004736 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004737 // use device for strategy enforced audible
4738 // 2: we are in call or the strategy phone is active on the output:
4739 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004740 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004741 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004742 // 4: the strategy for enforced audible is active but not enforced on the output:
4743 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004744 // 5: the strategy accessibility is active on the output:
4745 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004746 // 6: the strategy "respectful" sonification is active on the output:
4747 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004748 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004749 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004750 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004751 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004752 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004753 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004754 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004755 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004756 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4757 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004758 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004759 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004760 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004761 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004762 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4763 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004764 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4765 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004766 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004767 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004768 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004769 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004770 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004771 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004772 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004773 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004774 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004775 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004776 }
4777
Eric Laurent1c333e22014-05-20 10:48:17 -07004778 ALOGV("getNewOutputDevice() selected device %x", device);
4779 return device;
4780}
4781
Eric Laurentfb66dd92016-01-28 18:32:03 -08004782audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004783{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004784 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004785
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004786 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 if (index >= 0) {
4788 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4789 if (patchDesc->mUid != mUidCached) {
4790 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004791 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 return inputDesc->mDevice;
4793 }
4794 }
4795
Eric Laurentfb66dd92016-01-28 18:32:03 -08004796 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4797 if (isInCall()) {
4798 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4799 } else if (source != AUDIO_SOURCE_DEFAULT) {
4800 device = getDeviceAndMixForInputSource(source);
4801 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004802
Eric Laurente552edb2014-03-10 17:42:56 -07004803 return device;
4804}
4805
Eric Laurent794fde22016-03-11 09:50:45 -08004806bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4807 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004808 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004809}
4810
Eric Laurente0720872014-03-11 09:30:41 -07004811uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004812 return (uint32_t)getStrategy(stream);
4813}
4814
Eric Laurente0720872014-03-11 09:30:41 -07004815audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004816 // By checking the range of stream before calling getStrategy, we avoid
4817 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4818 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004819 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 return AUDIO_DEVICE_NONE;
4821 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004822 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004823 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4824 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 }
Eric Laurent794fde22016-03-11 09:50:45 -08004827 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004828 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004829 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004830 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4831 for (size_t i = 0; i < outputs.size(); i++) {
4832 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004833 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004834 curDevices |= outputDesc->device();
4835 }
4836 }
4837 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004838 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004839
4840 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4841 and doesn't really need to.*/
4842 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4843 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4844 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4845 }
Eric Laurente552edb2014-03-10 17:42:56 -07004846 return devices;
4847}
4848
François Gaffie2110e042015-03-24 08:41:51 +01004849routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4850{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004851 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004852 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004853}
4854
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004855uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4856 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004857 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4858 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4859 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004860 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4861 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4862 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004863 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004864 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004865}
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004869 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004870 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4871 updateDevicesAndOutputs();
4872 break;
4873 default:
4874 break;
4875 }
4876}
4877
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004878uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004879
4880 // skip beacon mute management if a dedicated TTS output is available
4881 if (mTtsOutputAvailable) {
4882 return 0;
4883 }
4884
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004885 switch(event) {
4886 case STARTING_OUTPUT:
4887 mBeaconMuteRefCount++;
4888 break;
4889 case STOPPING_OUTPUT:
4890 if (mBeaconMuteRefCount > 0) {
4891 mBeaconMuteRefCount--;
4892 }
4893 break;
4894 case STARTING_BEACON:
4895 mBeaconPlayingRefCount++;
4896 break;
4897 case STOPPING_BEACON:
4898 if (mBeaconPlayingRefCount > 0) {
4899 mBeaconPlayingRefCount--;
4900 }
4901 break;
4902 }
4903
4904 if (mBeaconMuteRefCount > 0) {
4905 // any playback causes beacon to be muted
4906 return setBeaconMute(true);
4907 } else {
4908 // no other playback: unmute when beacon starts playing, mute when it stops
4909 return setBeaconMute(mBeaconPlayingRefCount == 0);
4910 }
4911}
4912
4913uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4914 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4915 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4916 // keep track of muted state to avoid repeating mute/unmute operations
4917 if (mBeaconMuted != mute) {
4918 // mute/unmute AUDIO_STREAM_TTS on all outputs
4919 ALOGV("\t muting %d", mute);
4920 uint32_t maxLatency = 0;
4921 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004923 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004924 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004925 0 /*delay*/, AUDIO_DEVICE_NONE);
4926 const uint32_t latency = desc->latency() * 2;
4927 if (latency > maxLatency) {
4928 maxLatency = latency;
4929 }
4930 }
4931 mBeaconMuted = mute;
4932 return maxLatency;
4933 }
4934 return 0;
4935}
4936
Eric Laurente0720872014-03-11 09:30:41 -07004937audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004938 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004939{
Paul McLeanaa981192015-03-21 09:55:15 -07004940 // Routing
4941 // see if we have an explicit route
4942 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4943 // (getStrategy(stream)).
4944 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004945 // and activity count is non-zero and the device in the route descriptor is available
4946 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004947 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4948 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004949 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurentad2e7b92017-09-14 20:06:42 -07004950 if ((routeStrategy == strategy) && route->isActive() &&
4951 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004952 return route->mDeviceDescriptor->type();
4953 }
4954 }
4955
Eric Laurente552edb2014-03-10 17:42:56 -07004956 if (fromCache) {
4957 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4958 strategy, mDeviceForStrategy[strategy]);
4959 return mDeviceForStrategy[strategy];
4960 }
François Gaffie2110e042015-03-24 08:41:51 +01004961 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004962}
4963
Eric Laurente0720872014-03-11 09:30:41 -07004964void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004965{
4966 for (int i = 0; i < NUM_STRATEGIES; i++) {
4967 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4968 }
4969 mPreviousOutputs = mOutputs;
4970}
4971
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004972uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004973 audio_devices_t prevDevice,
4974 uint32_t delayMs)
4975{
4976 // mute/unmute strategies using an incompatible device combination
4977 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4978 // if unmuting, unmute only after the specified delay
4979 if (outputDesc->isDuplicated()) {
4980 return 0;
4981 }
4982
4983 uint32_t muteWaitMs = 0;
4984 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004985 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004986
4987 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4988 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004989 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004990 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4991 bool doMute = false;
4992
4993 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4994 doMute = true;
4995 outputDesc->mStrategyMutedByDevice[i] = true;
4996 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4997 doMute = true;
4998 outputDesc->mStrategyMutedByDevice[i] = false;
4999 }
Eric Laurent99401132014-05-07 19:48:15 -07005000 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005001 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005002 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005003 // skip output if it does not share any device with current output
5004 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5005 == AUDIO_DEVICE_NONE) {
5006 continue;
5007 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005008 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005009 mute ? "muting" : "unmuting", i, curDevice);
5010 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005011 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005012 if (mute) {
5013 // FIXME: should not need to double latency if volume could be applied
5014 // immediately by the audioflinger mixer. We must account for the delay
5015 // between now and the next time the audioflinger thread for this output
5016 // will process a buffer (which corresponds to one buffer size,
5017 // usually 1/2 or 1/4 of the latency).
5018 if (muteWaitMs < desc->latency() * 2) {
5019 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005020 }
5021 }
5022 }
5023 }
5024 }
5025 }
5026
Eric Laurent99401132014-05-07 19:48:15 -07005027 // temporary mute output if device selection changes to avoid volume bursts due to
5028 // different per device volumes
5029 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005030 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5031 // temporary mute duration is conservatively set to 4 times the reported latency
5032 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5033 if (muteWaitMs < tempMuteWaitMs) {
5034 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005035 }
Eric Laurentdc462862016-07-19 12:29:53 -07005036
Eric Laurent99401132014-05-07 19:48:15 -07005037 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005038 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005039 // make sure that we do not start the temporary mute period too early in case of
5040 // delayed device change
5041 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005042 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005043 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005044 }
5045 }
5046 }
5047
Eric Laurente552edb2014-03-10 17:42:56 -07005048 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5049 if (muteWaitMs > delayMs) {
5050 muteWaitMs -= delayMs;
5051 usleep(muteWaitMs * 1000);
5052 return muteWaitMs;
5053 }
5054 return 0;
5055}
5056
Eric Laurentc75307b2015-03-17 15:29:32 -07005057uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005058 audio_devices_t device,
5059 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005061 audio_patch_handle_t *patchHandle,
5062 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005063{
Eric Laurentc75307b2015-03-17 15:29:32 -07005064 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005065 AudioParameter param;
5066 uint32_t muteWaitMs;
5067
5068 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005069 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5070 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005071 return muteWaitMs;
5072 }
5073 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5074 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005075 if ((device != AUDIO_DEVICE_NONE) &&
5076 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005077 return 0;
5078 }
5079
5080 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005081 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005082
5083 audio_devices_t prevDevice = outputDesc->mDevice;
5084
Paul McLeanaa981192015-03-21 09:55:15 -07005085 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005086
5087 if (device != AUDIO_DEVICE_NONE) {
5088 outputDesc->mDevice = device;
5089 }
5090 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5091
5092 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005093 // the requested device is AUDIO_DEVICE_NONE
5094 // OR the requested device is the same as current device
5095 // AND force is not specified
5096 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005097 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005098 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5099 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005100 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005101 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005102 return muteWaitMs;
5103 }
5104
5105 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005106
Eric Laurente552edb2014-03-10 17:42:56 -07005107 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005108 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005109 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005110 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005111 DeviceVector deviceList;
5112 if ((address == NULL) || (strlen(address) == 0)) {
5113 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5114 } else {
5115 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5116 }
5117
Eric Laurent1c333e22014-05-20 10:48:17 -07005118 if (!deviceList.isEmpty()) {
5119 struct audio_patch patch;
5120 outputDesc->toAudioPortConfig(&patch.sources[0]);
5121 patch.num_sources = 1;
5122 patch.num_sinks = 0;
5123 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5124 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005125 patch.num_sinks++;
5126 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 ssize_t index;
5128 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5129 index = mAudioPatches.indexOfKey(*patchHandle);
5130 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005131 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 }
5133 sp< AudioPatch> patchDesc;
5134 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5135 if (index >= 0) {
5136 patchDesc = mAudioPatches.valueAt(index);
5137 afPatchHandle = patchDesc->mAfPatchHandle;
5138 }
5139
Eric Laurent1c333e22014-05-20 10:48:17 -07005140 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 &afPatchHandle,
5142 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005143 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5144 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005146 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005147 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005148 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005149 addAudioPatch(patchDesc->mHandle, patchDesc);
5150 } else {
5151 patchDesc->mPatch = patch;
5152 }
5153 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005154 if (patchHandle) {
5155 *patchHandle = patchDesc->mHandle;
5156 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005157 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005158 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005159 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005160 }
5161 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005162
5163 // inform all input as well
5164 for (size_t i = 0; i < mInputs.size(); i++) {
5165 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005166 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005167 AudioParameter inputCmd = AudioParameter();
5168 ALOGV("%s: inform input %d of device:%d", __func__,
5169 inputDescriptor->mIoHandle, device);
5170 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5171 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5172 inputCmd.toString(),
5173 delayMs);
5174 }
5175 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005176 }
Eric Laurente552edb2014-03-10 17:42:56 -07005177
5178 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005179 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005180
5181 return muteWaitMs;
5182}
5183
Eric Laurentc75307b2015-03-17 15:29:32 -07005184status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 int delayMs,
5186 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005187{
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 ssize_t index;
5189 if (patchHandle) {
5190 index = mAudioPatches.indexOfKey(*patchHandle);
5191 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005192 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 }
5194 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005195 return INVALID_OPERATION;
5196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5198 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005199 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005200 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 removeAudioPatch(patchDesc->mHandle);
5202 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005203 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 return status;
5205}
5206
5207status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5208 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 bool force,
5210 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005211{
5212 status_t status = NO_ERROR;
5213
Eric Laurent1f2f2232014-06-02 12:01:23 -07005214 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5216 inputDesc->mDevice = device;
5217
5218 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5219 if (!deviceList.isEmpty()) {
5220 struct audio_patch patch;
5221 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005222 // AUDIO_SOURCE_HOTWORD is for internal use only:
5223 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005224 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005225 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005226 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5227 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 patch.num_sinks = 1;
5229 //only one input device for now
5230 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005231 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 ssize_t index;
5233 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5234 index = mAudioPatches.indexOfKey(*patchHandle);
5235 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005236 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 }
5238 sp< AudioPatch> patchDesc;
5239 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5240 if (index >= 0) {
5241 patchDesc = mAudioPatches.valueAt(index);
5242 afPatchHandle = patchDesc->mAfPatchHandle;
5243 }
5244
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005247 0);
5248 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005250 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005252 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 addAudioPatch(patchDesc->mHandle, patchDesc);
5254 } else {
5255 patchDesc->mPatch = patch;
5256 }
5257 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 if (patchHandle) {
5259 *patchHandle = patchDesc->mHandle;
5260 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005261 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005263 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 }
5265 }
5266 }
5267 return status;
5268}
5269
Eric Laurent6a94d692014-05-20 11:18:06 -07005270status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5271 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005272{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005273 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 ssize_t index;
5275 if (patchHandle) {
5276 index = mAudioPatches.indexOfKey(*patchHandle);
5277 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005278 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 }
5280 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005281 return INVALID_OPERATION;
5282 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5284 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005285 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005286 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 removeAudioPatch(patchDesc->mHandle);
5288 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005289 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 return status;
5291}
5292
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005293sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005294 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005295 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005296 audio_format_t& format,
5297 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005298 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005299{
5300 // Choose an input profile based on the requested capture parameters: select the first available
5301 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005302 //
5303 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5304 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005305
5306 for (size_t i = 0; i < mHwModules.size(); i++)
5307 {
5308 if (mHwModules[i]->mHandle == 0) {
5309 continue;
5310 }
5311 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5312 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005314 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005315 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005316 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005317 format,
5318 &format /*updatedFormat*/,
5319 channelMask,
5320 &channelMask /*updatedChannelMask*/,
5321 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005322
Eric Laurente552edb2014-03-10 17:42:56 -07005323 return profile;
5324 }
5325 }
5326 }
5327 return NULL;
5328}
5329
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005330
5331audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005332 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005333{
François Gaffie036e1e92015-03-19 10:16:24 +01005334 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5335 audio_devices_t selectedDeviceFromMix =
5336 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005337
François Gaffie036e1e92015-03-19 10:16:24 +01005338 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5339 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005340 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005341 return getDeviceForInputSource(inputSource);
5342}
5343
5344audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5345{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005346 // Routing
5347 // Scan the whole RouteMap to see if we have an explicit route:
5348 // if the input source in the RouteMap is the same as the argument above,
5349 // and activity count is non-zero and the device in the route descriptor is available
5350 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005351 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5352 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurentad2e7b92017-09-14 20:06:42 -07005353 if ((inputSource == route->mSource) && route->isActive() &&
5354 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005355 return route->mDeviceDescriptor->type();
5356 }
5357 }
5358
5359 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005360}
5361
Eric Laurente0720872014-03-11 09:30:41 -07005362float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005363 int index,
5364 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005365{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005366 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005367
5368 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5369 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5370 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5371 // the ringtone volume
5372 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5373 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5374 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5375 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5376 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5377 }
5378
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005379 // in-call: always cap earpiece volume by voice volume + some low headroom
5380 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) && isInCall()) {
5381 switch (stream) {
5382 case AUDIO_STREAM_SYSTEM:
5383 case AUDIO_STREAM_RING:
5384 case AUDIO_STREAM_MUSIC:
5385 case AUDIO_STREAM_ALARM:
5386 case AUDIO_STREAM_NOTIFICATION:
5387 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5388 case AUDIO_STREAM_DTMF:
5389 case AUDIO_STREAM_ACCESSIBILITY: {
5390 const float maxVoiceVolDb = computeVolume(AUDIO_STREAM_VOICE_CALL, index, device)
5391 + IN_CALL_EARPIECE_HEADROOM_DB;
5392 if (volumeDB > maxVoiceVolDb) {
5393 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5394 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5395 volumeDB = maxVoiceVolDb;
5396 }
5397 } break;
5398 default:
5399 break;
5400 }
5401 }
5402
Eric Laurente552edb2014-03-10 17:42:56 -07005403 // if a headset is connected, apply the following rules to ring tones and notifications
5404 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005405 // - always attenuate notifications volume by 6dB
5406 // - attenuate ring tones volume by 6dB unless music is not playing and
5407 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005408 // - if music is playing, always limit the volume to current music volume,
5409 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005410 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005411 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5412 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5413 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005414 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5415 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005416 ((stream_strategy == STRATEGY_SONIFICATION)
5417 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005418 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005419 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005420 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005421 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005422 // when the phone is ringing we must consider that music could have been paused just before
5423 // by the music application and behave as if music was active if the last music track was
5424 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005425 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005426 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005427 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005428 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005429 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005430 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5431 musicDevice),
5432 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005433 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5434 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005435 if (volumeDB > minVolDB) {
5436 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005437 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005438 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005439 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5440 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5441 // on A2DP, also ensure notification volume is not too low compared to media when
5442 // intended to be played
5443 if ((volumeDB > -96.0f) &&
5444 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5445 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5446 stream, device,
5447 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5448 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5449 }
5450 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005451 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5452 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005453 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005454 }
5455 }
5456
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005457 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005458}
5459
Eric Laurente0720872014-03-11 09:30:41 -07005460status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005461 int index,
5462 const sp<AudioOutputDescriptor>& outputDesc,
5463 audio_devices_t device,
5464 int delayMs,
5465 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
Eric Laurente552edb2014-03-10 17:42:56 -07005467 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005468 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005469 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005470 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005471 return NO_ERROR;
5472 }
François Gaffie2110e042015-03-24 08:41:51 +01005473 audio_policy_forced_cfg_t forceUseForComm =
5474 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005475 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005476 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5477 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005478 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005479 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005480 return INVALID_OPERATION;
5481 }
5482
Eric Laurentc75307b2015-03-17 15:29:32 -07005483 if (device == AUDIO_DEVICE_NONE) {
5484 device = outputDesc->device();
5485 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005486
Eric Laurentffbc80f2015-03-18 18:30:19 -07005487 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005488 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005490 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005491
Eric Laurentffbc80f2015-03-18 18:30:19 -07005492 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005493
Eric Laurent3b73df72014-03-11 09:06:29 -07005494 if (stream == AUDIO_STREAM_VOICE_CALL ||
5495 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005496 float voiceVolume;
5497 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005498 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005499 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005500 } else {
5501 voiceVolume = 1.0;
5502 }
5503
Eric Laurent18fba842016-03-31 14:41:26 -07005504 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005505 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5506 mLastVoiceVolume = voiceVolume;
5507 }
5508 }
5509
5510 return NO_ERROR;
5511}
5512
Eric Laurentc75307b2015-03-17 15:29:32 -07005513void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5514 audio_devices_t device,
5515 int delayMs,
5516 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005517{
Eric Laurentc75307b2015-03-17 15:29:32 -07005518 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005519
Eric Laurent794fde22016-03-11 09:50:45 -08005520 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005521 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005522 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005523 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005524 device,
5525 delayMs,
5526 force);
5527 }
5528}
5529
Eric Laurente0720872014-03-11 09:30:41 -07005530void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005531 bool on,
5532 const sp<AudioOutputDescriptor>& outputDesc,
5533 int delayMs,
5534 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
Eric Laurent72249d52015-06-08 11:12:15 -07005536 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5537 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005538 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005539 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005540 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005541 }
5542 }
5543}
5544
Eric Laurente0720872014-03-11 09:30:41 -07005545void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005546 bool on,
5547 const sp<AudioOutputDescriptor>& outputDesc,
5548 int delayMs,
5549 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005550{
Eric Laurente552edb2014-03-10 17:42:56 -07005551 if (device == AUDIO_DEVICE_NONE) {
5552 device = outputDesc->device();
5553 }
5554
Eric Laurentc75307b2015-03-17 15:29:32 -07005555 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5556 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005557
5558 if (on) {
5559 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005560 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005561 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005562 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005564 }
5565 }
5566 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5567 outputDesc->mMuteCount[stream]++;
5568 } else {
5569 if (outputDesc->mMuteCount[stream] == 0) {
5570 ALOGV("setStreamMute() unmuting non muted stream!");
5571 return;
5572 }
5573 if (--outputDesc->mMuteCount[stream] == 0) {
5574 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005575 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005576 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005577 device,
5578 delayMs);
5579 }
5580 }
5581}
5582
Eric Laurente0720872014-03-11 09:30:41 -07005583void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005584 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005585{
Eric Laurent87ffa392015-05-22 10:32:38 -07005586 if(!hasPrimaryOutput()) {
5587 return;
5588 }
5589
Eric Laurente552edb2014-03-10 17:42:56 -07005590 // if the stream pertains to sonification strategy and we are in call we must
5591 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5592 // in the device used for phone strategy and play the tone if the selected device does not
5593 // interfere with the device used for phone strategy
5594 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5595 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005596 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005597 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5598 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005599 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005600 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5601 stream, starting, outputDesc->mDevice, stateChange);
5602 if (outputDesc->mRefCount[stream]) {
5603 int muteCount = 1;
5604 if (stateChange) {
5605 muteCount = outputDesc->mRefCount[stream];
5606 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005607 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005608 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5609 for (int i = 0; i < muteCount; i++) {
5610 setStreamMute(stream, starting, mPrimaryOutput);
5611 }
5612 } else {
5613 ALOGV("handleIncallSonification() high visibility");
5614 if (outputDesc->device() &
5615 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5616 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5617 for (int i = 0; i < muteCount; i++) {
5618 setStreamMute(stream, starting, mPrimaryOutput);
5619 }
5620 }
5621 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005622 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5623 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005624 } else {
5625 mpClientInterface->stopTone();
5626 }
5627 }
5628 }
5629 }
5630}
5631
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005632audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5633{
5634 // flags to stream type mapping
5635 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5636 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5637 }
5638 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5639 return AUDIO_STREAM_BLUETOOTH_SCO;
5640 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005641 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5642 return AUDIO_STREAM_TTS;
5643 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005644
5645 // usage to stream type mapping
5646 switch (attr->usage) {
5647 case AUDIO_USAGE_MEDIA:
5648 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005649 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005650 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5651 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005652 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5653 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005654 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5655 return AUDIO_STREAM_SYSTEM;
5656 case AUDIO_USAGE_VOICE_COMMUNICATION:
5657 return AUDIO_STREAM_VOICE_CALL;
5658
5659 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5660 return AUDIO_STREAM_DTMF;
5661
5662 case AUDIO_USAGE_ALARM:
5663 return AUDIO_STREAM_ALARM;
5664 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5665 return AUDIO_STREAM_RING;
5666
5667 case AUDIO_USAGE_NOTIFICATION:
5668 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5669 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5670 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5671 case AUDIO_USAGE_NOTIFICATION_EVENT:
5672 return AUDIO_STREAM_NOTIFICATION;
5673
5674 case AUDIO_USAGE_UNKNOWN:
5675 default:
5676 return AUDIO_STREAM_MUSIC;
5677 }
5678}
Eric Laurente83b55d2014-11-14 10:06:21 -08005679
François Gaffie53615e22015-03-19 09:24:12 +01005680bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5681{
Eric Laurente83b55d2014-11-14 10:06:21 -08005682 // has flags that map to a strategy?
5683 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5684 return true;
5685 }
5686
5687 // has known usage?
5688 switch (paa->usage) {
5689 case AUDIO_USAGE_UNKNOWN:
5690 case AUDIO_USAGE_MEDIA:
5691 case AUDIO_USAGE_VOICE_COMMUNICATION:
5692 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5693 case AUDIO_USAGE_ALARM:
5694 case AUDIO_USAGE_NOTIFICATION:
5695 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5696 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5697 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5698 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5699 case AUDIO_USAGE_NOTIFICATION_EVENT:
5700 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5701 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5702 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5703 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005704 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005705 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005706 break;
5707 default:
5708 return false;
5709 }
5710 return true;
5711}
5712
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005713bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005714 routing_strategy strategy, uint32_t inPastMs,
5715 nsecs_t sysTime) const
5716{
5717 if ((sysTime == 0) && (inPastMs != 0)) {
5718 sysTime = systemTime();
5719 }
Eric Laurent794fde22016-03-11 09:50:45 -08005720 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005721 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5722 (NUM_STRATEGIES == strategy)) &&
5723 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5724 return true;
5725 }
5726 }
5727 return false;
5728}
5729
François Gaffie2110e042015-03-24 08:41:51 +01005730audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5731{
5732 return mEngine->getForceUse(usage);
5733}
5734
5735bool AudioPolicyManager::isInCall()
5736{
5737 return isStateInCall(mEngine->getPhoneState());
5738}
5739
5740bool AudioPolicyManager::isStateInCall(int state)
5741{
5742 return is_state_in_call(state);
5743}
5744
Eric Laurentd60560a2015-04-10 11:31:20 -07005745void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5746{
5747 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5748 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5749 if (sourceDesc->mDevice->equals(deviceDesc)) {
5750 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5751 stopAudioSource(sourceDesc->getHandle());
5752 }
5753 }
5754
5755 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5756 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5757 bool release = false;
5758 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5759 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5760 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5761 source->ext.device.type == deviceDesc->type()) {
5762 release = true;
5763 }
5764 }
5765 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5766 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5767 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5768 sink->ext.device.type == deviceDesc->type()) {
5769 release = true;
5770 }
5771 }
5772 if (release) {
5773 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5774 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5775 }
5776 }
5777}
5778
Phil Burk09bc4612016-02-24 15:58:15 -08005779// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005780void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5781 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005782 // TODO Set this based on Config properties.
5783 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005784
5785 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5786 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005787 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005788
5789 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005790 bool supportsAC3 = false;
5791 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005792 bool supportsIEC61937 = false;
5793 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5794 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005795 switch (format) {
5796 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005797 supportsAC3 = true;
5798 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005799 case AUDIO_FORMAT_E_AC3:
5800 case AUDIO_FORMAT_DTS:
5801 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005802 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005803 break;
5804 case AUDIO_FORMAT_IEC61937:
5805 supportsIEC61937 = true;
5806 break;
5807 default:
5808 break;
5809 }
5810 }
Phil Burk09bc4612016-02-24 15:58:15 -08005811
5812 // Modify formats based on surround preferences.
5813 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5815 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5816 // Remove surround sound related formats.
5817 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5818 audio_format_t format = formats[formatIndex];
5819 switch(format) {
5820 case AUDIO_FORMAT_AC3:
5821 case AUDIO_FORMAT_E_AC3:
5822 case AUDIO_FORMAT_DTS:
5823 case AUDIO_FORMAT_DTS_HD:
5824 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005825 formats.removeAt(formatIndex);
5826 break;
5827 default:
5828 formatIndex++; // keep it
5829 break;
5830 }
Phil Burk09bc4612016-02-24 15:58:15 -08005831 }
Phil Burk07ac1142016-03-25 13:39:29 -07005832 supportsAC3 = false;
5833 supportsOtherSurround = false;
5834 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005835 }
Phil Burk07ac1142016-03-25 13:39:29 -07005836 } else { // AUTO or ALWAYS
5837 // Most TVs support AC3 even if they do not report it in the EDID.
5838 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5839 && !supportsAC3) {
5840 formats.add(AUDIO_FORMAT_AC3);
5841 supportsAC3 = true;
5842 }
5843
5844 // If ALWAYS, add support for raw surround formats if all are missing.
5845 // This assumes that if any of these formats are reported by the HAL
5846 // then the report is valid and should not be modified.
5847 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5848 && !supportsOtherSurround) {
5849 formats.add(AUDIO_FORMAT_E_AC3);
5850 formats.add(AUDIO_FORMAT_DTS);
5851 formats.add(AUDIO_FORMAT_DTS_HD);
5852 supportsOtherSurround = true;
5853 }
5854
5855 // Add support for IEC61937 if any raw surround supported.
5856 // The HAL could do this but add it here, just in case.
5857 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5858 formats.add(AUDIO_FORMAT_IEC61937);
5859 supportsIEC61937 = true;
5860 }
Phil Burk09bc4612016-02-24 15:58:15 -08005861 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005862}
5863
5864// Modify the list of channel masks supported.
5865void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5866 ChannelsVector &channelMasks = *channelMasksPtr;
5867 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5868 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5869
5870 // If NEVER, then remove support for channelMasks > stereo.
5871 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5872 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5873 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5874 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5875 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5876 channelMasks.removeAt(maskIndex);
5877 } else {
5878 maskIndex++;
5879 }
5880 }
5881 // If ALWAYS, then make sure we at least support 5.1
5882 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5883 bool supports5dot1 = false;
5884 // Are there any channel masks that can be considered "surround"?
5885 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5886 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5887 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5888 supports5dot1 = true;
5889 break;
5890 }
5891 }
5892 // If not then add 5.1 support.
5893 if (!supports5dot1) {
5894 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5895 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5896 }
Phil Burk09bc4612016-02-24 15:58:15 -08005897 }
5898}
5899
Phil Burk00eeb322016-03-31 12:41:00 -07005900void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5901 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005902 AudioProfileVector &profiles)
5903{
5904 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005905
François Gaffie112b0af2015-11-19 16:13:25 +01005906 // Format MUST be checked first to update the list of AudioProfile
5907 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005908 reply = mpClientInterface->getParameters(
5909 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005910 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005911 AudioParameter repliedParameters(reply);
5912 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005913 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005914 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5915 return;
5916 }
Phil Burk09bc4612016-02-24 15:58:15 -08005917 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005918 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005919 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005920 }
Phil Burk09bc4612016-02-24 15:58:15 -08005921 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005922 }
5923 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5924
Eric Laurent20eb3a42016-01-26 18:39:17 -08005925 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005926 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005927 ChannelsVector channelMasks;
5928 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005929 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005930 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005931
5932 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005933 reply = mpClientInterface->getParameters(
5934 ioHandle,
5935 requestedParameters.toString() + ";" +
5936 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005937 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005938 AudioParameter repliedParameters(reply);
5939 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005940 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005941 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005942 }
5943 }
5944 if (profiles.hasDynamicChannelsFor(format)) {
5945 reply = mpClientInterface->getParameters(ioHandle,
5946 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005947 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005948 ALOGV("%s: supported channel masks %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::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005952 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005953 if (device == AUDIO_DEVICE_OUT_HDMI) {
5954 filterSurroundChannelMasks(&channelMasks);
5955 }
François Gaffie112b0af2015-11-19 16:13:25 +01005956 }
5957 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005958 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005959 }
5960}
Eric Laurentd60560a2015-04-10 11:31:20 -07005961
Eric Laurente552edb2014-03-10 17:42:56 -07005962}; // namespace android