blob: d0cfa5a443e8c648f7e73ce38721ea1d186f40b4 [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
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurentdc462862016-07-19 12:29:53 -070052//FIXME: workaround for truncated touch sounds
53// to be removed when the problem is handled by system UI
54#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070055// ----------------------------------------------------------------------------
56// AudioPolicyInterface implementation
57// ----------------------------------------------------------------------------
58
Eric Laurente0720872014-03-11 09:30:41 -070059status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080060 audio_policy_dev_state_t state,
61 const char *device_address,
62 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070063{
Paul McLeane743a472015-01-28 11:07:31 -080064 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080065}
66
François Gaffie44481e72016-04-20 07:49:57 +020067void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
68 audio_policy_dev_state_t state,
69 const String8 &device_address)
70{
71 AudioParameter param(device_address);
72 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
73 AUDIO_PARAMETER_DEVICE_CONNECT : AUDIO_PARAMETER_DEVICE_DISCONNECT);
74 param.addInt(key, device);
75 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
76}
77
Eric Laurentc73ca6e2014-12-12 14:34:22 -080078status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080079 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080080 const char *device_address,
81 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080082{
Paul McLeane743a472015-01-28 11:07:31 -080083 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
84- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070085
86 // connect/disconnect only 1 device at a time
87 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
88
François Gaffie53615e22015-03-19 09:24:12 +010089 sp<DeviceDescriptor> devDesc =
90 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080091
Eric Laurente552edb2014-03-10 17:42:56 -070092 // handle output devices
93 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070094 SortedVector <audio_io_handle_t> outputs;
95
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
97
Eric Laurente552edb2014-03-10 17:42:56 -070098 // save a copy of the opened output descriptors before any output is opened or closed
99 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
100 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700101 switch (state)
102 {
103 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800104 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700105 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700106 ALOGW("setDeviceConnectionState() device already connected: %x", device);
107 return INVALID_OPERATION;
108 }
109 ALOGV("setDeviceConnectionState() connecting device %x", device);
110
Eric Laurente552edb2014-03-10 17:42:56 -0700111 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700112 index = mAvailableOutputDevices.add(devDesc);
113 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100114 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700115 if (module == 0) {
116 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
117 device);
118 mAvailableOutputDevices.remove(devDesc);
119 return INVALID_OPERATION;
120 }
Paul McLeane743a472015-01-28 11:07:31 -0800121 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700122 } else {
123 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 }
125
François Gaffie44481e72016-04-20 07:49:57 +0200126 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
127 // parameters on newly connected devices (instead of opening the outputs...)
128 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
129
Eric Laurenta1d525f2015-01-29 13:36:45 -0800130 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700131 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200132
133 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
134 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700135 return INVALID_OPERATION;
136 }
François Gaffie2110e042015-03-24 08:41:51 +0100137 // Propagate device availability to Engine
138 mEngine->setDeviceConnectionState(devDesc, state);
139
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700140 // outputs should never be empty here
141 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
142 "checkOutputsForDevice() returned no outputs but status OK");
143 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
144 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800145
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700148 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700150 ALOGW("setDeviceConnectionState() device not connected: %x", device);
151 return INVALID_OPERATION;
152 }
153
Paul McLean5c477aa2014-08-20 16:47:57 -0700154 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
155
Paul McLeane743a472015-01-28 11:07:31 -0800156 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200157 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700158
Eric Laurente552edb2014-03-10 17:42:56 -0700159 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700160 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100163
164 // Propagate device availability to Engine
165 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700166 } break;
167
168 default:
169 ALOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
174 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700175 checkA2dpSuspend();
176 checkOutputForAllStrategies();
177 // outputs must be closed after checkOutputForAllStrategies() is executed
178 if (!outputs.isEmpty()) {
179 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700180 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // close unused outputs after device disconnection or direct outputs that have been
182 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700184 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
185 (desc->mDirectOpenCount == 0))) {
186 closeOutput(outputs[i]);
187 }
188 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189 // check again after closing A2DP output to reset mA2dpSuspended if needed
190 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
193 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700194 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700195 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
196 updateCallRouting(newDevice);
197 }
Eric Laurente552edb2014-03-10 17:42:56 -0700198 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700199 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
200 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
201 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700202 // do not force device change on duplicated output because if device is 0, it will
203 // also force a device 0 for the two outputs it is duplicated to which may override
204 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700205 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100206 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700207 // always force when disconnecting (a non-duplicated device)
208 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700209 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700210 }
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
Eric Laurentd60560a2015-04-10 11:31:20 -0700213 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
214 cleanUpForDevice(devDesc);
215 }
216
Eric Laurent72aa32f2014-05-30 18:51:48 -0700217 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700218 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700219 } // end if is output device
220
Eric Laurente552edb2014-03-10 17:42:56 -0700221 // handle input devices
222 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700223 SortedVector <audio_io_handle_t> inputs;
224
Eric Laurent3a4311c2014-03-17 12:00:47 -0700225 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700226 switch (state)
227 {
228 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700231 ALOGW("setDeviceConnectionState() device already connected: %d", device);
232 return INVALID_OPERATION;
233 }
François Gaffie53615e22015-03-19 09:24:12 +0100234 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700235 if (module == NULL) {
236 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
237 device);
238 return INVALID_OPERATION;
239 }
François Gaffie44481e72016-04-20 07:49:57 +0200240
241 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
242 // parameters on newly connected devices (instead of opening the inputs...)
243 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
244
Paul McLean9080a4c2015-06-18 08:24:02 -0700245 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200246 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
247 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700248 return INVALID_OPERATION;
249 }
250
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 index = mAvailableInputDevices.add(devDesc);
252 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800253 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 } else {
255 return NO_MEMORY;
256 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800257
François Gaffie2110e042015-03-24 08:41:51 +0100258 // Propagate device availability to Engine
259 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700260 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700261
262 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700263 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700265 ALOGW("setDeviceConnectionState() device not connected: %d", device);
266 return INVALID_OPERATION;
267 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700268
269 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
270
271 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200272 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700273
Paul McLean9080a4c2015-06-18 08:24:02 -0700274 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700276
François Gaffie2110e042015-03-24 08:41:51 +0100277 // Propagate device availability to Engine
278 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 default:
282 ALOGE("setDeviceConnectionState() invalid state: %x", state);
283 return BAD_VALUE;
284 }
285
Eric Laurentd4692962014-05-05 18:13:44 -0700286 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700287 // As the input device list can impact the output device selection, update
288 // getDeviceForStrategy() cache
289 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700290
Eric Laurent87ffa392015-05-22 10:32:38 -0700291 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700292 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
293 updateCallRouting(newDevice);
294 }
295
Eric Laurentd60560a2015-04-10 11:31:20 -0700296 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
297 cleanUpForDevice(devDesc);
298 }
299
Eric Laurentb52c1522014-05-20 11:27:36 -0700300 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 ALOGW("setDeviceConnectionState() invalid device: %x", device);
305 return BAD_VALUE;
306}
307
Eric Laurente0720872014-03-11 09:30:41 -0700308audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100309 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700310{
Eric Laurent634b7142016-04-20 13:48:02 -0700311 sp<DeviceDescriptor> devDesc =
312 mHwModules.getDeviceDescriptor(device, device_address, "",
313 (strlen(device_address) != 0)/*matchAddress*/);
314
315 if (devDesc == 0) {
316 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
317 device, device_address);
318 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
319 }
François Gaffie53615e22015-03-19 09:24:12 +0100320
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 DeviceVector *deviceVector;
322
Eric Laurente552edb2014-03-10 17:42:56 -0700323 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700324 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700325 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 deviceVector = &mAvailableInputDevices;
327 } else {
328 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
329 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700330 }
Eric Laurent634b7142016-04-20 13:48:02 -0700331
332 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
333 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800334}
335
Eric Laurentdc462862016-07-19 12:29:53 -0700336uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337{
338 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 status_t status;
340 audio_patch_handle_t afPatchHandle;
341 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700342 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700343
Eric Laurent87ffa392015-05-22 10:32:38 -0700344 if(!hasPrimaryOutput()) {
Eric Laurentdc462862016-07-19 12:29:53 -0700345 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700346 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800347 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700348 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
349
350 // release existing RX patch if any
351 if (mCallRxPatch != 0) {
352 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
353 mCallRxPatch.clear();
354 }
355 // release TX patch if any
356 if (mCallTxPatch != 0) {
357 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
358 mCallTxPatch.clear();
359 }
360
361 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
362 // via setOutputDevice() on primary output.
363 // Otherwise, create two audio patches for TX and RX path.
364 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700365 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700366 // If the TX device is also on the primary HW module, setOutputDevice() will take care
367 // of it due to legacy implementation. If not, create a patch.
368 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
369 == AUDIO_DEVICE_NONE) {
370 createTxPatch = true;
371 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700372 } else { // create RX path audio patch
373 struct audio_patch patch;
374
375 patch.num_sources = 1;
376 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700377 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
378 ALOG_ASSERT(!deviceList.isEmpty(),
379 "updateCallRouting() selected device not in output device list");
380 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
381 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
382 ALOG_ASSERT(!deviceList.isEmpty(),
383 "updateCallRouting() no telephony RX device");
384 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
385
386 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
387 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
388
389 // request to reuse existing output stream if one is already opened to reach the RX device
390 SortedVector<audio_io_handle_t> outputs =
391 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700392 audio_io_handle_t output = selectOutput(outputs,
393 AUDIO_OUTPUT_FLAG_NONE,
394 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700395 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700397 ALOG_ASSERT(!outputDesc->isDuplicated(),
398 "updateCallRouting() RX device output is duplicated");
399 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700400 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700401 patch.num_sources = 2;
402 }
403
404 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700405 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700406 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
407 status);
408 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100409 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700410 mCallRxPatch->mAfPatchHandle = afPatchHandle;
411 mCallRxPatch->mUid = mUidCached;
412 }
413 createTxPatch = true;
414 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700415 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700417
Eric Laurentc2730ba2014-07-20 15:47:07 -0700418 patch.num_sources = 1;
419 patch.num_sinks = 1;
420 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
421 ALOG_ASSERT(!deviceList.isEmpty(),
422 "updateCallRouting() selected device not in input device list");
423 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
424 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
425 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
426 ALOG_ASSERT(!deviceList.isEmpty(),
427 "updateCallRouting() no telephony TX device");
428 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
429 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
430
431 SortedVector<audio_io_handle_t> outputs =
432 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700433 audio_io_handle_t output = selectOutput(outputs,
434 AUDIO_OUTPUT_FLAG_NONE,
435 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436 // request to reuse existing output stream if one is already opened to reach the TX
437 // path output device
438 if (output != AUDIO_IO_HANDLE_NONE) {
439 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
440 ALOG_ASSERT(!outputDesc->isDuplicated(),
441 "updateCallRouting() RX device output is duplicated");
442 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700443 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700444 patch.num_sources = 2;
445 }
446
Eric Laurentc0a889f2015-10-14 14:36:34 -0700447 // terminate active capture if on the same HW module as the call TX source device
448 // FIXME: would be better to refine to only inputs whose profile connects to the
449 // call TX device but this information is not in the audio patch and logic here must be
450 // symmetric to the one in startInput()
Eric Laurent232f26f2016-02-17 18:06:27 -0800451 audio_io_handle_t activeInput = mInputs.getActiveInput();
452 if (activeInput != 0) {
453 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
454 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
455 //FIXME: consider all active sessions
456 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
457 audio_session_t activeSession = activeSessions.keyAt(0);
458 stopInput(activeInput, activeSession);
459 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700460 }
461 }
462
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700464 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700465 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
466 status);
467 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100468 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469 mCallTxPatch->mAfPatchHandle = afPatchHandle;
470 mCallTxPatch->mUid = mUidCached;
471 }
472 }
Eric Laurentdc462862016-07-19 12:29:53 -0700473
474 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475}
476
Eric Laurente0720872014-03-11 09:30:41 -0700477void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700478{
479 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100480 // store previous phone state for management of sonification strategy below
481 int oldState = mEngine->getPhoneState();
482
483 if (mEngine->setPhoneState(state) != NO_ERROR) {
484 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700485 return;
486 }
François Gaffie2110e042015-03-24 08:41:51 +0100487 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700488 // if leaving call state, handle special case of active streams
489 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700490 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700491 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800492 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700493 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700494 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800495
Eric Laurent63dea1d2015-07-02 17:10:28 -0700496 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800497 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700498 }
499
François Gaffie2110e042015-03-24 08:41:51 +0100500 /**
501 * Switching to or from incall state or switching between telephony and VoIP lead to force
502 * routing command.
503 */
504 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
505 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700506
507 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700508 checkA2dpSuspend();
509 checkOutputForAllStrategies();
510 updateDevicesAndOutputs();
511
Eric Laurente552edb2014-03-10 17:42:56 -0700512 int delayMs = 0;
513 if (isStateInCall(state)) {
514 nsecs_t sysTime = systemTime();
515 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700516 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700517 // mute media and sonification strategies and delay device switch by the largest
518 // latency of any output where either strategy is active.
519 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100520 if ((isStrategyActive(desc, STRATEGY_MEDIA,
521 SONIFICATION_HEADSET_MUSIC_DELAY,
522 sysTime) ||
523 isStrategyActive(desc, STRATEGY_SONIFICATION,
524 SONIFICATION_HEADSET_MUSIC_DELAY,
525 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700526 (delayMs < (int)desc->latency()*2)) {
527 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700528 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700529 setStrategyMute(STRATEGY_MEDIA, true, desc);
530 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700531 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700532 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
533 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700534 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
535 }
536 }
537
Eric Laurent87ffa392015-05-22 10:32:38 -0700538 if (hasPrimaryOutput()) {
539 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
540 // the device returned is not necessarily reachable via this output
541 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
542 // force routing command to audio hardware when ending call
543 // even if no device change is needed
544 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
545 rxDevice = mPrimaryOutput->device();
546 }
Eric Laurente552edb2014-03-10 17:42:56 -0700547
Eric Laurent87ffa392015-05-22 10:32:38 -0700548 if (state == AUDIO_MODE_IN_CALL) {
549 updateCallRouting(rxDevice, delayMs);
550 } else if (oldState == AUDIO_MODE_IN_CALL) {
551 if (mCallRxPatch != 0) {
552 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
553 mCallRxPatch.clear();
554 }
555 if (mCallTxPatch != 0) {
556 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
557 mCallTxPatch.clear();
558 }
559 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
560 } else {
561 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700562 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700563 }
Eric Laurente552edb2014-03-10 17:42:56 -0700564 // if entering in call state, handle special case of active streams
565 // pertaining to sonification strategy see handleIncallSonification()
566 if (isStateInCall(state)) {
567 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800568 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700569 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700571
572 // force reevaluating accessibility routing when call starts
573 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700574 }
575
576 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700577 if (state == AUDIO_MODE_RINGTONE &&
578 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700579 mLimitRingtoneVolume = true;
580 } else {
581 mLimitRingtoneVolume = false;
582 }
583}
584
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700585audio_mode_t AudioPolicyManager::getPhoneState() {
586 return mEngine->getPhoneState();
587}
588
Eric Laurente0720872014-03-11 09:30:41 -0700589void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700590 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700591{
François Gaffie2110e042015-03-24 08:41:51 +0100592 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700593
François Gaffie2110e042015-03-24 08:41:51 +0100594 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
595 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
596 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700597 }
François Gaffie2110e042015-03-24 08:41:51 +0100598 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
599 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
600 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700601
602 // check for device and output changes triggered by new force usage
603 checkA2dpSuspend();
604 checkOutputForAllStrategies();
605 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800606
Eric Laurentdc462862016-07-19 12:29:53 -0700607 //FIXME: workaround for truncated touch sounds
608 // to be removed when the problem is handled by system UI
609 uint32_t delayMs = 0;
610 uint32_t waitMs = 0;
611 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
612 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
613 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700614 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700615 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700616 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617 }
Eric Laurente552edb2014-03-10 17:42:56 -0700618 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700619 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
620 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
621 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700622 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
623 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700624 }
Eric Laurente552edb2014-03-10 17:42:56 -0700625 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700626 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700627 }
628 }
629
Eric Laurent232f26f2016-02-17 18:06:27 -0800630 audio_io_handle_t activeInput = mInputs.getActiveInput();
631 if (activeInput != 0) {
632 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
633 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700634 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800635 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
636 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700637 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800638 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700639 }
Eric Laurente552edb2014-03-10 17:42:56 -0700640 }
Eric Laurente552edb2014-03-10 17:42:56 -0700641}
642
Eric Laurente0720872014-03-11 09:30:41 -0700643void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700644{
645 ALOGV("setSystemProperty() property %s, value %s", property, value);
646}
647
648// Find a direct output profile compatible with the parameters passed, even if the input flags do
649// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800650sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700651 audio_devices_t device,
652 uint32_t samplingRate,
653 audio_format_t format,
654 audio_channel_mask_t channelMask,
655 audio_output_flags_t flags)
656{
Eric Laurent861a6282015-05-18 15:40:16 -0700657 // only retain flags that will drive the direct output profile selection
658 // if explicitly requested
659 static const uint32_t kRelevantFlags =
660 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
661 flags =
662 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
663
664 sp<IOProfile> profile;
665
Eric Laurente552edb2014-03-10 17:42:56 -0700666 for (size_t i = 0; i < mHwModules.size(); i++) {
667 if (mHwModules[i]->mHandle == 0) {
668 continue;
669 }
670 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700671 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
672 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700673 samplingRate, NULL /*updatedSamplingRate*/,
674 format, NULL /*updatedFormat*/,
675 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700676 flags)) {
677 continue;
678 }
679 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100680 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700681 continue;
682 }
683 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100684 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700685 continue;
686 }
687 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100688 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700689 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700690 }
Eric Laurente552edb2014-03-10 17:42:56 -0700691 }
692 }
Eric Laurent861a6282015-05-18 15:40:16 -0700693 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700694}
695
Eric Laurente0720872014-03-11 09:30:41 -0700696audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100697 uint32_t samplingRate,
698 audio_format_t format,
699 audio_channel_mask_t channelMask,
700 audio_output_flags_t flags,
701 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700702{
Eric Laurent3b73df72014-03-11 09:06:29 -0700703 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700704 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
705 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
706 device, stream, samplingRate, format, channelMask, flags);
707
Eric Laurente83b55d2014-11-14 10:06:21 -0800708 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
709 stream, samplingRate,format, channelMask,
710 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700711}
712
Eric Laurente83b55d2014-11-14 10:06:21 -0800713status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
714 audio_io_handle_t *output,
715 audio_session_t session,
716 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700717 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800718 uint32_t samplingRate,
719 audio_format_t format,
720 audio_channel_mask_t channelMask,
721 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700722 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800723 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700724{
Eric Laurente83b55d2014-11-14 10:06:21 -0800725 audio_attributes_t attributes;
726 if (attr != NULL) {
727 if (!isValidAttributes(attr)) {
728 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
729 attr->usage, attr->content_type, attr->flags,
730 attr->tags);
731 return BAD_VALUE;
732 }
733 attributes = *attr;
734 } else {
735 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
736 ALOGE("getOutputForAttr(): invalid stream type");
737 return BAD_VALUE;
738 }
739 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700740 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700741 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800742 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100743 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800744 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100745 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800746 }
François Gaffie036e1e92015-03-19 10:16:24 +0100747 *stream = streamTypefromAttributesInt(&attributes);
748 *output = desc->mIoHandle;
749 ALOGV("getOutputForAttr() returns output %d", *output);
750 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800751 }
752 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
753 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
754 return BAD_VALUE;
755 }
756
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700757 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
758 " session %d selectedDeviceId %d",
759 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
760 session, selectedDeviceId);
761
762 *stream = streamTypefromAttributesInt(&attributes);
763
764 // Explicit routing?
765 sp<DeviceDescriptor> deviceDesc;
766 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
767 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
768 deviceDesc = mAvailableOutputDevices[i];
769 break;
770 }
771 }
772 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700773
Eric Laurente83b55d2014-11-14 10:06:21 -0800774 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700775 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700778 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
779 }
780
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700781 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700782 device, samplingRate, format, channelMask, flags);
783
Eric Laurente83b55d2014-11-14 10:06:21 -0800784 *output = getOutputForDevice(device, session, *stream,
785 samplingRate, format, channelMask,
786 flags, offloadInfo);
787 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700788 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800789 return INVALID_OPERATION;
790 }
Paul McLeanaa981192015-03-21 09:55:15 -0700791
Eric Laurente83b55d2014-11-14 10:06:21 -0800792 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793}
794
795audio_io_handle_t AudioPolicyManager::getOutputForDevice(
796 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800797 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700798 audio_stream_type_t stream,
799 uint32_t samplingRate,
800 audio_format_t format,
801 audio_channel_mask_t channelMask,
802 audio_output_flags_t flags,
803 const audio_offload_info_t *offloadInfo)
804{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700805 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700806 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700807
Eric Laurente552edb2014-03-10 17:42:56 -0700808#ifdef AUDIO_POLICY_TEST
809 if (mCurOutput != 0) {
810 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
811 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
812
813 if (mTestOutputs[mCurOutput] == 0) {
814 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700815 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
816 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700818 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700819 outputDesc->mFlags =
820 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700822 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
823 config.sample_rate = mTestSamplingRate;
824 config.channel_mask = mTestChannels;
825 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700826 if (offloadInfo != NULL) {
827 config.offload_info = *offloadInfo;
828 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700829 status = mpClientInterface->openOutput(0,
830 &mTestOutputs[mCurOutput],
831 &config,
832 &outputDesc->mDevice,
833 String8(""),
834 &outputDesc->mLatency,
835 outputDesc->mFlags);
836 if (status == NO_ERROR) {
837 outputDesc->mSamplingRate = config.sample_rate;
838 outputDesc->mFormat = config.format;
839 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700840 AudioParameter outputCmd = AudioParameter();
841 outputCmd.addInt(String8("set_id"),mCurOutput);
842 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
843 addOutput(mTestOutputs[mCurOutput], outputDesc);
844 }
845 }
846 return mTestOutputs[mCurOutput];
847 }
848#endif //AUDIO_POLICY_TEST
849
850 // open a direct output if required by specified parameters
851 //force direct flag if offload flag is set: offloading implies a direct output stream
852 // and all common behaviors are driven by checking only the direct flag
853 // this should normally be set appropriately in the policy configuration file
854 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700855 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700856 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700857 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
858 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
859 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 // only allow deep buffering for music stream type
861 if (stream != AUDIO_STREAM_MUSIC) {
862 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700863 } else if (/* stream == AUDIO_STREAM_MUSIC && */
864 flags == AUDIO_OUTPUT_FLAG_NONE &&
865 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
866 // use DEEP_BUFFER as default output for music stream type
867 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800868 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700869 if (stream == AUDIO_STREAM_TTS) {
870 flags = AUDIO_OUTPUT_FLAG_TTS;
871 }
Eric Laurente552edb2014-03-10 17:42:56 -0700872
Eric Laurentb732cf52014-09-24 19:08:21 -0700873 sp<IOProfile> profile;
874
875 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700876 // and not explicitly requested
877 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800878 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700879 audio_channel_count_from_out_mask(channelMask) <= 2) {
880 goto non_direct_output;
881 }
882
Andy Hung2ddee192015-12-18 17:34:44 -0800883 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
884 // This prevents creating an offloaded track and tearing it down immediately after start
885 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700886 // FIXME: We should check the audio session here but we do not have it in this context.
887 // This may prevent offloading in rare situations where effects are left active by apps
888 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800891 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700892 profile = getProfileForDirectOutput(device,
893 samplingRate,
894 format,
895 channelMask,
896 (audio_output_flags_t)flags);
897 }
898
Eric Laurent1c333e22014-05-20 10:48:17 -0700899 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700900 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700901
902 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700904 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
905 outputDesc = desc;
906 // reuse direct output if currently open and configured with same parameters
907 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800908 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700909 (channelMask == outputDesc->mChannelMask)) {
910 outputDesc->mDirectOpenCount++;
911 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
912 return mOutputs.keyAt(i);
913 }
914 }
915 }
916 // close direct output if currently open and configured with different parameters
917 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Eric Laurent861a6282015-05-18 15:40:16 -0700920
921 // if the selected profile is offloaded and no offload info was specified,
922 // create a default one
923 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100924 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700925 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
926 defaultOffloadInfo.sample_rate = samplingRate;
927 defaultOffloadInfo.channel_mask = channelMask;
928 defaultOffloadInfo.format = format;
929 defaultOffloadInfo.stream_type = stream;
930 defaultOffloadInfo.bit_rate = 0;
931 defaultOffloadInfo.duration_us = -1;
932 defaultOffloadInfo.has_video = true; // conservative
933 defaultOffloadInfo.is_streaming = true; // likely
934 offloadInfo = &defaultOffloadInfo;
935 }
936
Eric Laurentc75307b2015-03-17 15:29:32 -0700937 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700939 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700940 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700941 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
942 config.sample_rate = samplingRate;
943 config.channel_mask = channelMask;
944 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700945 if (offloadInfo != NULL) {
946 config.offload_info = *offloadInfo;
947 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700948 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700949 &output,
950 &config,
951 &outputDesc->mDevice,
952 String8(""),
953 &outputDesc->mLatency,
954 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700955
956 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700957 if (status != NO_ERROR ||
958 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800959 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700961 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
962 "format %d %d, channelMask %04x %04x", output, samplingRate,
963 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
964 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700965 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700966 mpClientInterface->closeOutput(output);
967 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800968 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800969 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800970 goto non_direct_output;
971 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700974 outputDesc->mSamplingRate = config.sample_rate;
975 outputDesc->mChannelMask = config.channel_mask;
976 outputDesc->mFormat = config.format;
977 outputDesc->mRefCount[stream] = 0;
978 outputDesc->mStopTime[stream] = 0;
979 outputDesc->mDirectOpenCount = 1;
980
Eric Laurente552edb2014-03-10 17:42:56 -0700981 audio_io_handle_t srcOutput = getOutputForEffect();
982 addOutput(output, outputDesc);
983 audio_io_handle_t dstOutput = getOutputForEffect();
984 if (dstOutput == output) {
985 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
986 }
987 mPreviousOutputs = mOutputs;
988 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700989 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700990 return output;
991 }
992
Eric Laurentb732cf52014-09-24 19:08:21 -0700993non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700994
995 // A request for HW A/V sync cannot fallback to a mixed output because time
996 // stamps are embedded in audio data
997 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
998 return AUDIO_IO_HANDLE_NONE;
999 }
1000
Eric Laurente552edb2014-03-10 17:42:56 -07001001 // ignoring channel mask due to downmix capability in mixer
1002
1003 // open a non direct output
1004
1005 // for non direct outputs, only PCM is supported
1006 if (audio_is_linear_pcm(format)) {
1007 // get which output is suitable for the specified stream. The actual
1008 // routing change will happen when startOutput() will be called
1009 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1010
Eric Laurent8838a382014-09-08 16:44:28 -07001011 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1012 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1013 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
1015 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1016 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1017
Paul McLeanaa981192015-03-21 09:55:15 -07001018 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001019
1020 return output;
1021}
1022
Eric Laurente0720872014-03-11 09:30:41 -07001023audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001024 audio_output_flags_t flags,
1025 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001026{
1027 // select one output among several that provide a path to a particular device or set of
1028 // devices (the list was previously build by getOutputsForDevice()).
1029 // The priority is as follows:
1030 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001031 // 2: the output with the bit depth the closest to the requested one
1032 // 3: the primary output
1033 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 if (outputs.size() == 0) {
1036 return 0;
1037 }
1038 if (outputs.size() == 1) {
1039 return outputs[0];
1040 }
1041
1042 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001043 audio_io_handle_t outputForFlags = 0;
1044 audio_io_handle_t outputForPrimary = 0;
1045 audio_io_handle_t outputForFormat = 0;
1046 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1047 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001048
1049 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001050 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001051 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001052 // if a valid format is specified, skip output if not compatible
1053 if (format != AUDIO_FORMAT_INVALID) {
1054 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001055 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001056 continue;
1057 }
1058 } else if (!audio_is_linear_pcm(format)) {
1059 continue;
1060 }
Eric Laurente6930022016-02-11 10:20:40 -08001061 if (AudioPort::isBetterFormatMatch(
1062 outputDesc->mFormat, bestFormat, format)) {
1063 outputForFormat = outputs[i];
1064 bestFormat = outputDesc->mFormat;
1065 }
Eric Laurent8838a382014-09-08 16:44:28 -07001066 }
1067
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001068 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001069 if (commonFlags >= maxCommonFlags) {
1070 if (commonFlags == maxCommonFlags) {
1071 if (AudioPort::isBetterFormatMatch(
1072 outputDesc->mFormat, bestFormatForFlags, format)) {
1073 outputForFlags = outputs[i];
1074 bestFormatForFlags = outputDesc->mFormat;
1075 }
1076 } else {
1077 outputForFlags = outputs[i];
1078 maxCommonFlags = commonFlags;
1079 bestFormatForFlags = outputDesc->mFormat;
1080 }
Eric Laurente552edb2014-03-10 17:42:56 -07001081 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1082 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001083 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001084 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 }
1087 }
1088
Eric Laurente6930022016-02-11 10:20:40 -08001089 if (outputForFlags != 0) {
1090 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001091 }
Eric Laurente6930022016-02-11 10:20:40 -08001092 if (outputForFormat != 0) {
1093 return outputForFormat;
1094 }
1095 if (outputForPrimary != 0) {
1096 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001097 }
1098
1099 return outputs[0];
1100}
1101
Eric Laurente0720872014-03-11 09:30:41 -07001102status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001103 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001104 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001105{
Paul McLeanaa981192015-03-21 09:55:15 -07001106 ALOGV("startOutput() output %d, stream %d, session %d",
1107 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001108 ssize_t index = mOutputs.indexOfKey(output);
1109 if (index < 0) {
1110 ALOGW("startOutput() unknown output %d", output);
1111 return BAD_VALUE;
1112 }
1113
Eric Laurentc75307b2015-03-17 15:29:32 -07001114 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1115
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001116 // Routing?
1117 mOutputRoutes.incRouteActivity(session);
1118
Eric Laurentc75307b2015-03-17 15:29:32 -07001119 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001120 AudioMix *policyMix = NULL;
1121 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001122 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001123 policyMix = outputDesc->mPolicyMix;
1124 address = policyMix->mDeviceAddress.string();
1125 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1126 newDevice = policyMix->mDeviceType;
1127 } else {
1128 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1129 }
Eric Laurent493404d2015-04-21 15:07:36 -07001130 } else if (mOutputRoutes.hasRouteChanged(session)) {
1131 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001132 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001133 } else {
1134 newDevice = AUDIO_DEVICE_NONE;
1135 }
1136
1137 uint32_t delayMs = 0;
1138
Eric Laurentc40d9692016-04-13 19:14:13 -07001139 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001140
1141 if (status != NO_ERROR) {
1142 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001143 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001144 }
1145 // Automatically enable the remote submix input when output is started on a re routing mix
1146 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001147 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1148 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001149 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001151 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001152 "remote-submix");
1153 }
1154
1155 if (delayMs != 0) {
1156 usleep(delayMs * 1000);
1157 }
1158
1159 return status;
1160}
1161
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001162status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001163 audio_stream_type_t stream,
1164 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001165 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 uint32_t *delayMs)
1167{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001168 // cannot start playback of STREAM_TTS if any other output is being used
1169 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001170
1171 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001172 if (stream == AUDIO_STREAM_TTS) {
1173 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001174 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001175 return INVALID_OPERATION;
1176 } else {
1177 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1178 }
1179 } else {
1180 // some playback other than beacon starts
1181 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1182 }
1183
Eric Laurent77305a62016-07-25 16:39:22 -07001184 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001185 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001186 bool force = !outputDesc->isActive() &&
1187 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001188
Eric Laurente552edb2014-03-10 17:42:56 -07001189 // increment usage count for this stream on the requested output:
1190 // NOTE that the usage count is the same for duplicated output and hardware output which is
1191 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1192 outputDesc->changeRefCount(stream, 1);
1193
Eric Laurent493404d2015-04-21 15:07:36 -07001194 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001195 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001196 if (device == AUDIO_DEVICE_NONE) {
1197 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001198 }
Eric Laurente552edb2014-03-10 17:42:56 -07001199 routing_strategy strategy = getStrategy(stream);
1200 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001201 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1202 (beaconMuteLatency > 0);
1203 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001204 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001205 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001206 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001207 // force a device change if any other output is:
1208 // - managed by the same hw module
1209 // - has a current device selection that differs from selected device.
1210 // - supports currently selected device
1211 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001212 // In this case, the audio HAL must receive the new device selection so that it can
1213 // change the device currently selected by the other active output.
1214 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001215 desc->device() != device &&
1216 desc->supportedDevices() & device &&
1217 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001218 force = true;
1219 }
1220 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001221 // a notification so that audio focus effect can propagate, or that a mute/unmute
1222 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001223 uint32_t latency = desc->latency();
1224 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1225 waitMs = latency;
1226 }
1227 }
1228 }
Eric Laurentdc462862016-07-19 12:29:53 -07001229 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001230
1231 // handle special case for sonification while in call
1232 if (isInCall()) {
1233 handleIncallSonification(stream, true, false);
1234 }
1235
1236 // apply volume rules for current stream and device if necessary
1237 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001238 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001239 outputDesc,
1240 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001241
1242 // update the outputs if starting an output with a stream that can affect notification
1243 // routing
1244 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001245
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001246 // force reevaluating accessibility routing when ringtone or alarm starts
1247 if (strategy == STRATEGY_SONIFICATION) {
1248 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1249 }
Eric Laurentdc462862016-07-19 12:29:53 -07001250
1251 if (waitMs > muteWaitMs) {
1252 *delayMs = waitMs - muteWaitMs;
1253 }
Eric Laurente552edb2014-03-10 17:42:56 -07001254 }
Eric Laurentdc462862016-07-19 12:29:53 -07001255
Eric Laurente552edb2014-03-10 17:42:56 -07001256 return NO_ERROR;
1257}
1258
1259
Eric Laurente0720872014-03-11 09:30:41 -07001260status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001261 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001262 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001263{
1264 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1265 ssize_t index = mOutputs.indexOfKey(output);
1266 if (index < 0) {
1267 ALOGW("stopOutput() unknown output %d", output);
1268 return BAD_VALUE;
1269 }
1270
Eric Laurentc75307b2015-03-17 15:29:32 -07001271 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001272
Eric Laurentc75307b2015-03-17 15:29:32 -07001273 if (outputDesc->mRefCount[stream] == 1) {
1274 // Automatically disable the remote submix input when output is stopped on a
1275 // re routing mix of type MIX_TYPE_RECORDERS
1276 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1277 outputDesc->mPolicyMix != NULL &&
1278 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1279 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1280 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001281 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001282 "remote-submix");
1283 }
1284 }
1285
1286 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001288 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001289 int activityCount = mOutputRoutes.decRouteActivity(session);
1290 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1291
1292 if (forceDeviceUpdate) {
1293 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1294 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001295 }
1296
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001297 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001298}
1299
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07001300status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001301 audio_stream_type_t stream,
1302 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001303{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001304 // always handle stream stop, check which stream type is stopping
1305 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1306
Eric Laurente552edb2014-03-10 17:42:56 -07001307 // handle special case for sonification while in call
1308 if (isInCall()) {
1309 handleIncallSonification(stream, false, false);
1310 }
1311
1312 if (outputDesc->mRefCount[stream] > 0) {
1313 // decrement usage count of this stream on the output
1314 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001317 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001318 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001319 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 // delay the device switch by twice the latency because stopOutput() is executed when
1321 // the track stop() command is received and at that time the audio track buffer can
1322 // still contain data that needs to be drained. The latency only covers the audio HAL
1323 // and kernel buffers. Also the latency does not always include additional delay in the
1324 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001326
1327 // force restoring the device selection on other active outputs if it differs from the
1328 // one being selected for this output
1329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001330 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001332 desc->isActive() &&
1333 outputDesc->sharesHwModuleWith(desc) &&
1334 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001335 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1336 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001337 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001338 newDevice2,
1339 force,
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001341 }
1342 }
1343 // update the outputs if stopping one with a stream that can affect notification routing
1344 handleNotificationRoutingForStream(stream);
1345 }
1346 return NO_ERROR;
1347 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001348 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001349 return INVALID_OPERATION;
1350 }
1351}
1352
Eric Laurente83b55d2014-11-14 10:06:21 -08001353void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001354 audio_stream_type_t stream __unused,
1355 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001356{
1357 ALOGV("releaseOutput() %d", output);
1358 ssize_t index = mOutputs.indexOfKey(output);
1359 if (index < 0) {
1360 ALOGW("releaseOutput() releasing unknown output %d", output);
1361 return;
1362 }
1363
1364#ifdef AUDIO_POLICY_TEST
1365 int testIndex = testOutputIndex(output);
1366 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001367 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001368 if (outputDesc->isActive()) {
1369 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001370 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001371 mTestOutputs[testIndex] = 0;
1372 }
1373 return;
1374 }
1375#endif //AUDIO_POLICY_TEST
1376
Paul McLeanaa981192015-03-21 09:55:15 -07001377 // Routing
1378 mOutputRoutes.removeRoute(session);
1379
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001381 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001382 if (desc->mDirectOpenCount <= 0) {
1383 ALOGW("releaseOutput() invalid open count %d for output %d",
1384 desc->mDirectOpenCount, output);
1385 return;
1386 }
1387 if (--desc->mDirectOpenCount == 0) {
1388 closeOutput(output);
1389 // If effects where present on the output, audioflinger moved them to the primary
1390 // output by default: move them back to the appropriate output.
1391 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001392 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001393 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1394 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001395 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001396 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001397 }
1398 }
1399}
1400
1401
Eric Laurentcaf7f482014-11-25 17:50:47 -08001402status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1403 audio_io_handle_t *input,
1404 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001405 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001406 uint32_t samplingRate,
1407 audio_format_t format,
1408 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001409 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001410 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001411 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001412{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001413 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1414 "session %d, flags %#x",
1415 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001416
Eric Laurentcaf7f482014-11-25 17:50:47 -08001417 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001418 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001419 audio_devices_t device;
1420 // handle legacy remote submix case where the address was not always specified
1421 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001422 audio_source_t inputSource = attr->source;
1423 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001424 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001425
Eric Laurentc447ded2015-01-06 08:47:05 -08001426 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1427 inputSource = AUDIO_SOURCE_MIC;
1428 }
1429 halInputSource = inputSource;
1430
Paul McLean466dc8e2015-04-17 13:15:36 -06001431 // Explicit routing?
1432 sp<DeviceDescriptor> deviceDesc;
1433 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1434 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1435 deviceDesc = mAvailableInputDevices[i];
1436 break;
1437 }
1438 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001439 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001440
Eric Laurentc447ded2015-01-06 08:47:05 -08001441 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001442 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001443 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001444 if (ret != NO_ERROR) {
1445 return ret;
1446 }
1447 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001448 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1449 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001450 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001451 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001452 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001453 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001454 return BAD_VALUE;
1455 }
Eric Laurentc722f302014-12-10 11:21:49 -08001456 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001457 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001458 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1459 // there is an external policy, but this input is attached to a mix of recorders,
1460 // meaning it receives audio injected into the framework, so the recorder doesn't
1461 // know about it and is therefore considered "legacy"
1462 *inputType = API_INPUT_LEGACY;
1463 } else {
1464 // recording a mix of players defined by an external policy, we're rerouting for
1465 // an external policy
1466 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1467 }
Eric Laurentc722f302014-12-10 11:21:49 -08001468 } else if (audio_is_remote_submix_device(device)) {
1469 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001470 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001471 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1472 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001473 } else {
1474 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001475 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001476
Eric Laurent599c7582015-12-07 18:05:55 -08001477 }
1478
1479 *input = getInputForDevice(device, address, session, uid, inputSource,
1480 samplingRate, format, channelMask, flags,
1481 policyMix);
1482 if (*input == AUDIO_IO_HANDLE_NONE) {
1483 mInputRoutes.removeRoute(session);
1484 return INVALID_OPERATION;
1485 }
1486 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1487 return NO_ERROR;
1488}
1489
1490
1491audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1492 String8 address,
1493 audio_session_t session,
1494 uid_t uid,
1495 audio_source_t inputSource,
1496 uint32_t samplingRate,
1497 audio_format_t format,
1498 audio_channel_mask_t channelMask,
1499 audio_input_flags_t flags,
1500 AudioMix *policyMix)
1501{
1502 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1503 audio_source_t halInputSource = inputSource;
1504 bool isSoundTrigger = false;
1505
1506 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1507 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1508 if (index >= 0) {
1509 input = mSoundTriggerSessions.valueFor(session);
1510 isSoundTrigger = true;
1511 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1512 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1513 } else {
1514 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001515 }
1516 }
1517
Andy Hungf129b032015-04-07 13:45:50 -07001518 // find a compatible input profile (not necessarily identical in parameters)
1519 sp<IOProfile> profile;
1520 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001521 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001522 audio_format_t profileFormat = format;
1523 audio_channel_mask_t profileChannelMask = channelMask;
1524 audio_input_flags_t profileFlags = flags;
1525 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001526 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001527 profileSamplingRate, profileFormat, profileChannelMask,
1528 profileFlags);
1529 if (profile != 0) {
1530 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001531 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1532 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001533 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1534 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1535 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001536 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1537 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001538 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001539 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001540 }
Eric Laurente552edb2014-03-10 17:42:56 -07001541 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001542 // Pick input sampling rate if not specified by client
1543 if (samplingRate == 0) {
1544 samplingRate = profileSamplingRate;
1545 }
Eric Laurente552edb2014-03-10 17:42:56 -07001546
Eric Laurent322b4d22015-04-03 15:57:54 -07001547 if (profile->getModuleHandle() == 0) {
1548 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001549 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001550 }
1551
Eric Laurent599c7582015-12-07 18:05:55 -08001552 sp<AudioSession> audioSession = new AudioSession(session,
1553 inputSource,
1554 format,
1555 samplingRate,
1556 channelMask,
1557 flags,
1558 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001559 isSoundTrigger,
1560 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001561
Eric Laurent232f26f2016-02-17 18:06:27 -08001562// TODO enable input reuse
1563#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001564 // reuse an open input if possible
1565 for (size_t i = 0; i < mInputs.size(); i++) {
1566 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001567 // reuse input if it shares the same profile and same sound trigger attribute
1568 if (profile == desc->mProfile &&
1569 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001570
1571 sp<AudioSession> as = desc->getAudioSession(session);
1572 if (as != 0) {
1573 // do not allow unmatching properties on same session
1574 if (as->matches(audioSession)) {
1575 as->changeOpenCount(1);
1576 } else {
1577 ALOGW("getInputForDevice() record with different attributes"
1578 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001579 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001580 }
1581 } else {
1582 desc->addAudioSession(session, audioSession);
1583 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001584 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1585 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001586 }
1587 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001588#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001589
Eric Laurentcf2c0212014-07-25 16:20:43 -07001590 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001591 config.sample_rate = profileSamplingRate;
1592 config.channel_mask = profileChannelMask;
1593 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001594
Eric Laurent322b4d22015-04-03 15:57:54 -07001595 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001596 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001597 &config,
1598 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001599 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001600 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001601 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001602
1603 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001604 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001605 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001606 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001607 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001608 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1609 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001610 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001611 if (input != AUDIO_IO_HANDLE_NONE) {
1612 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001613 }
Eric Laurent599c7582015-12-07 18:05:55 -08001614 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001615 }
1616
Eric Laurent1f2f2232014-06-02 12:01:23 -07001617 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001618 inputDesc->mSamplingRate = profileSamplingRate;
1619 inputDesc->mFormat = profileFormat;
1620 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001621 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001622 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001623 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001624
Eric Laurent599c7582015-12-07 18:05:55 -08001625 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001626 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001627
Eric Laurent599c7582015-12-07 18:05:55 -08001628 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001629}
1630
Eric Laurent4dc68062014-07-28 17:26:49 -07001631status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001632 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001633{
1634 ALOGV("startInput() input %d", input);
1635 ssize_t index = mInputs.indexOfKey(input);
1636 if (index < 0) {
1637 ALOGW("startInput() unknown input %d", input);
1638 return BAD_VALUE;
1639 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001640 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001641
Eric Laurent599c7582015-12-07 18:05:55 -08001642 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1643 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001644 ALOGW("startInput() unknown session %d on input %d", session, input);
1645 return BAD_VALUE;
1646 }
1647
Eric Laurent232f26f2016-02-17 18:06:27 -08001648 // virtual input devices are compatible with other input devices
1649 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001650
Eric Laurent232f26f2016-02-17 18:06:27 -08001651 // for a non-virtual input device, check if there is another (non-virtual) active input
1652 audio_io_handle_t activeInput = mInputs.getActiveInput();
1653 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001654
Eric Laurent232f26f2016-02-17 18:06:27 -08001655 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1656 // otherwise the active input continues and the new input cannot be started.
1657 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1658 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1659 !activeDesc->hasPreemptedSession(session)) {
1660 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1661 //FIXME: consider all active sessions
1662 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1663 audio_session_t activeSession = activeSessions.keyAt(0);
1664 SortedVector<audio_session_t> sessions =
1665 activeDesc->getPreemptedSessions();
1666 sessions.add(activeSession);
1667 inputDesc->setPreemptedSessions(sessions);
1668 stopInput(activeInput, activeSession);
1669 releaseInput(activeInput, activeSession);
1670 } else {
1671 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1672 return INVALID_OPERATION;
1673 }
1674 }
1675
1676 // Do not allow capture if an active voice call is using a software patch and
1677 // the call TX source device is on the same HW module.
1678 // FIXME: would be better to refine to only inputs whose profile connects to the
1679 // call TX device but this information is not in the audio patch
1680 if (mCallTxPatch != 0 &&
1681 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1682 return INVALID_OPERATION;
1683 }
1684 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001685
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001686 // Routing?
1687 mInputRoutes.incRouteActivity(session);
1688
Eric Laurent232f26f2016-02-17 18:06:27 -08001689 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1690 // if input maps to a dynamic policy with an activity listener, notify of state change
1691 if ((inputDesc->mPolicyMix != NULL)
1692 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001693 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001694 MIX_STATE_MIXING);
1695 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001696
Eric Laurent232f26f2016-02-17 18:06:27 -08001697 if (mInputs.activeInputsCount() == 0) {
1698 SoundTrigger::setCaptureState(true);
1699 }
1700 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001701
Eric Laurent232f26f2016-02-17 18:06:27 -08001702 // automatically enable the remote submix output when input is started if not
1703 // used by a policy mix of type MIX_TYPE_RECORDERS
1704 // For remote submix (a virtual device), we open only one input per capture request.
1705 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1706 String8 address = String8("");
1707 if (inputDesc->mPolicyMix == NULL) {
1708 address = String8("0");
1709 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001710 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001711 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001712 if (address != "") {
1713 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1714 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1715 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001716 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001717 }
Eric Laurente552edb2014-03-10 17:42:56 -07001718 }
1719
Eric Laurent599c7582015-12-07 18:05:55 -08001720 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001721
Eric Laurent232f26f2016-02-17 18:06:27 -08001722 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001723 return NO_ERROR;
1724}
1725
Eric Laurent4dc68062014-07-28 17:26:49 -07001726status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1727 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001728{
1729 ALOGV("stopInput() input %d", input);
1730 ssize_t index = mInputs.indexOfKey(input);
1731 if (index < 0) {
1732 ALOGW("stopInput() unknown input %d", input);
1733 return BAD_VALUE;
1734 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001735 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001736
Eric Laurent599c7582015-12-07 18:05:55 -08001737 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001738 if (index < 0) {
1739 ALOGW("stopInput() unknown session %d on input %d", session, input);
1740 return BAD_VALUE;
1741 }
1742
Eric Laurent599c7582015-12-07 18:05:55 -08001743 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001744 ALOGW("stopInput() input %d already stopped", input);
1745 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001746 }
1747
Eric Laurent599c7582015-12-07 18:05:55 -08001748 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001749
1750 // Routing?
1751 mInputRoutes.decRouteActivity(session);
1752
Eric Laurent232f26f2016-02-17 18:06:27 -08001753 if (!inputDesc->isActive()) {
1754 // if input maps to a dynamic policy with an activity listener, notify of state change
1755 if ((inputDesc->mPolicyMix != NULL)
1756 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001757 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001758 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001759 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001760
1761 // automatically disable the remote submix output when input is stopped if not
1762 // used by a policy mix of type MIX_TYPE_RECORDERS
1763 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1764 String8 address = String8("");
1765 if (inputDesc->mPolicyMix == NULL) {
1766 address = String8("0");
1767 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001768 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent232f26f2016-02-17 18:06:27 -08001769 }
1770 if (address != "") {
1771 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1772 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1773 address, "remote-submix");
1774 }
1775 }
1776
1777 resetInputDevice(input);
1778
1779 if (mInputs.activeInputsCount() == 0) {
1780 SoundTrigger::setCaptureState(false);
1781 }
1782 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001783 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001784 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001785}
1786
Eric Laurent4dc68062014-07-28 17:26:49 -07001787void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1788 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001789{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001790
Eric Laurente552edb2014-03-10 17:42:56 -07001791 ALOGV("releaseInput() %d", input);
1792 ssize_t index = mInputs.indexOfKey(input);
1793 if (index < 0) {
1794 ALOGW("releaseInput() releasing unknown input %d", input);
1795 return;
1796 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001797
1798 // Routing
1799 mInputRoutes.removeRoute(session);
1800
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001801 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1802 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001803
Eric Laurent599c7582015-12-07 18:05:55 -08001804 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001805 if (index < 0) {
1806 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1807 return;
1808 }
Eric Laurent599c7582015-12-07 18:05:55 -08001809
1810 if (audioSession->openCount() == 0) {
1811 ALOGW("releaseInput() invalid open count %d on session %d",
1812 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001813 return;
1814 }
Eric Laurent599c7582015-12-07 18:05:55 -08001815
1816 if (audioSession->changeOpenCount(-1) == 0) {
1817 inputDesc->removeAudioSession(session);
1818 }
1819
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001820 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001821 ALOGV("releaseInput() exit > 0");
1822 return;
1823 }
1824
Eric Laurent05b90f82014-08-27 15:32:29 -07001825 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001826 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001827 ALOGV("releaseInput() exit");
1828}
1829
Eric Laurentd4692962014-05-05 18:13:44 -07001830void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001831 bool patchRemoved = false;
1832
Eric Laurentd4692962014-05-05 18:13:44 -07001833 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001834 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001835 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001836 if (patch_index >= 0) {
1837 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001838 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001839 mAudioPatches.removeItemsAt(patch_index);
1840 patchRemoved = true;
1841 }
Eric Laurentd4692962014-05-05 18:13:44 -07001842 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1843 }
1844 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001845 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001846 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001847
1848 if (patchRemoved) {
1849 mpClientInterface->onAudioPatchListUpdate();
1850 }
Eric Laurentd4692962014-05-05 18:13:44 -07001851}
1852
Eric Laurente0720872014-03-11 09:30:41 -07001853void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001854 int indexMin,
1855 int indexMax)
1856{
1857 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001858 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001859
1860 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001861 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1862 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001863 continue;
1864 }
1865 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867}
1868
Eric Laurente0720872014-03-11 09:30:41 -07001869status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001870 int index,
1871 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001872{
1873
François Gaffied1ab2bd2015-12-02 18:20:06 +01001874 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1875 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001876 return BAD_VALUE;
1877 }
1878 if (!audio_is_output_device(device)) {
1879 return BAD_VALUE;
1880 }
1881
1882 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001883 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001884
Eric Laurent1fd372e2016-04-06 14:23:53 -07001885 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001886 stream, device, index);
1887
Eric Laurent28d09f02016-03-08 10:43:05 -08001888 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001889 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1890 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001891 continue;
1892 }
1893 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1894 }
Eric Laurente552edb2014-03-10 17:42:56 -07001895
Eric Laurent1fd372e2016-04-06 14:23:53 -07001896 // update volume on all outputs and streams matching the following:
1897 // - The requested stream (or a stream matching for volume control) is active on the output
1898 // - The device (or devices) selected by the strategy corresponding to this stream includes
1899 // the requested device
1900 // - For non default requested device, currently selected device on the output is either the
1901 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001902 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1903 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001904 status_t status = NO_ERROR;
1905 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1907 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001908 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1909 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001910 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001911 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001912 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1913 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001914 continue;
1915 }
Eric Laurent794fde22016-03-11 09:50:45 -08001916 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08001917 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
Eric Laurent1fd372e2016-04-06 14:23:53 -07001918 if ((curStreamDevice & device) == 0) {
1919 continue;
1920 }
1921 bool applyDefault = false;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001922 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001923 curStreamDevice |= device;
1924 } else if (!mVolumeCurves->hasVolumeIndexForDevice(
1925 stream, Volume::getDeviceForVolume(curStreamDevice))) {
1926 applyDefault = true;
1927 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001928
Eric Laurent1fd372e2016-04-06 14:23:53 -07001929 if (applyDefault || ((curDevice & curStreamDevice) != 0)) {
Eric Laurentdc462862016-07-19 12:29:53 -07001930 //FIXME: workaround for truncated touch sounds
1931 // delayed volume change for system stream to be removed when the problem is
1932 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08001933 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07001934 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
1935 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08001936 if (volStatus != NO_ERROR) {
1937 status = volStatus;
1938 }
1939 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001940 }
Eric Laurente552edb2014-03-10 17:42:56 -07001941 }
1942 return status;
1943}
1944
Eric Laurente0720872014-03-11 09:30:41 -07001945status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001946 int *index,
1947 audio_devices_t device)
1948{
1949 if (index == NULL) {
1950 return BAD_VALUE;
1951 }
1952 if (!audio_is_output_device(device)) {
1953 return BAD_VALUE;
1954 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07001955 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07001956 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07001957 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07001958 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1959 }
François Gaffiedfd74092015-03-19 12:10:59 +01001960 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001961
François Gaffied1ab2bd2015-12-02 18:20:06 +01001962 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001963 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1964 return NO_ERROR;
1965}
1966
Eric Laurente0720872014-03-11 09:30:41 -07001967audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001968 const SortedVector<audio_io_handle_t>& outputs)
1969{
1970 // select one output among several suitable for global effects.
1971 // The priority is as follows:
1972 // 1: An offloaded output. If the effect ends up not being offloadable,
1973 // AudioFlinger will invalidate the track and the offloaded output
1974 // will be closed causing the effect to be moved to a PCM output.
1975 // 2: A deep buffer output
1976 // 3: the first output in the list
1977
1978 if (outputs.size() == 0) {
1979 return 0;
1980 }
1981
1982 audio_io_handle_t outputOffloaded = 0;
1983 audio_io_handle_t outputDeepBuffer = 0;
1984
1985 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001986 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001987 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001988 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1989 outputOffloaded = outputs[i];
1990 }
1991 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1992 outputDeepBuffer = outputs[i];
1993 }
1994 }
1995
1996 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1997 outputOffloaded, outputDeepBuffer);
1998 if (outputOffloaded != 0) {
1999 return outputOffloaded;
2000 }
2001 if (outputDeepBuffer != 0) {
2002 return outputDeepBuffer;
2003 }
2004
2005 return outputs[0];
2006}
2007
Eric Laurente0720872014-03-11 09:30:41 -07002008audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002009{
2010 // apply simple rule where global effects are attached to the same output as MUSIC streams
2011
Eric Laurent3b73df72014-03-11 09:06:29 -07002012 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002013 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2014 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2015
2016 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2017 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2018 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2019
2020 return output;
2021}
2022
Eric Laurente0720872014-03-11 09:30:41 -07002023status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002024 audio_io_handle_t io,
2025 uint32_t strategy,
2026 int session,
2027 int id)
2028{
2029 ssize_t index = mOutputs.indexOfKey(io);
2030 if (index < 0) {
2031 index = mInputs.indexOfKey(io);
2032 if (index < 0) {
2033 ALOGW("registerEffect() unknown io %d", io);
2034 return INVALID_OPERATION;
2035 }
2036 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002037 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002038}
2039
Eric Laurentc75307b2015-03-17 15:29:32 -07002040bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2041{
Eric Laurent28d09f02016-03-08 10:43:05 -08002042 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002043 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2044 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002045 continue;
2046 }
2047 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2048 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002049 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002050}
2051
2052bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2053{
2054 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2055}
2056
Eric Laurente0720872014-03-11 09:30:41 -07002057bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002058{
2059 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002060 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002061 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002062 return true;
2063 }
2064 }
2065 return false;
2066}
2067
Eric Laurent275e8e92014-11-30 15:14:47 -08002068// Register a list of custom mixes with their attributes and format.
2069// When a mix is registered, corresponding input and output profiles are
2070// added to the remote submix hw module. The profile contains only the
2071// parameters (sampling rate, format...) specified by the mix.
2072// The corresponding input remote submix device is also connected.
2073//
2074// When a remote submix device is connected, the address is checked to select the
2075// appropriate profile and the corresponding input or output stream is opened.
2076//
2077// When capture starts, getInputForAttr() will:
2078// - 1 look for a mix matching the address passed in attribtutes tags if any
2079// - 2 if none found, getDeviceForInputSource() will:
2080// - 2.1 look for a mix matching the attributes source
2081// - 2.2 if none found, default to device selection by policy rules
2082// At this time, the corresponding output remote submix device is also connected
2083// and active playback use cases can be transferred to this mix if needed when reconnecting
2084// after AudioTracks are invalidated
2085//
2086// When playback starts, getOutputForAttr() will:
2087// - 1 look for a mix matching the address passed in attribtutes tags if any
2088// - 2 if none found, look for a mix matching the attributes usage
2089// - 3 if none found, default to device and output selection by policy rules.
2090
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07002091status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002092{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002093 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2094 status_t res = NO_ERROR;
2095
2096 sp<HwModule> rSubmixModule;
2097 // examine each mix's route type
2098 for (size_t i = 0; i < mixes.size(); i++) {
2099 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2100 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2101 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002102 break;
2103 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002104 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2105 // Loop back through "remote submix"
2106 if (rSubmixModule == 0) {
2107 for (size_t j = 0; i < mHwModules.size(); j++) {
2108 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2109 && mHwModules[j]->mHandle != 0) {
2110 rSubmixModule = mHwModules[j];
2111 break;
2112 }
2113 }
2114 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002115
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002116 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002117
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002118 if (rSubmixModule == 0) {
2119 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2120 res = INVALID_OPERATION;
2121 break;
2122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002123
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002124 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002125
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002126 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002127 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002128 res = INVALID_OPERATION;
2129 break;
2130 }
2131 audio_config_t outputConfig = mixes[i].mFormat;
2132 audio_config_t inputConfig = mixes[i].mFormat;
2133 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2134 // stereo and let audio flinger do the channel conversion if needed.
2135 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2136 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2137 rSubmixModule->addOutputProfile(address, &outputConfig,
2138 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2139 rSubmixModule->addInputProfile(address, &inputConfig,
2140 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002141
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002142 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2143 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2144 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2145 address.string(), "remote-submix");
2146 } else {
2147 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2148 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2149 address.string(), "remote-submix");
2150 }
2151 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002152 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002153 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002154 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2155 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002156
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002157 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002158 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2159 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2160 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2161 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2162 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2163 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002164 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2165 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002166 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2167 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002168 } else {
2169 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002170 }
2171 break;
2172 }
2173 }
2174
2175 if (res != NO_ERROR) {
2176 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002177 i, device, address.string());
2178 res = INVALID_OPERATION;
2179 break;
2180 } else if (!foundOutput) {
2181 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2182 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002183 res = INVALID_OPERATION;
2184 break;
2185 }
Eric Laurentc722f302014-12-10 11:21:49 -08002186 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002187 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002188 if (res != NO_ERROR) {
2189 unregisterPolicyMixes(mixes);
2190 }
2191 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002192}
2193
2194status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2195{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002196 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002197 status_t res = NO_ERROR;
2198 sp<HwModule> rSubmixModule;
2199 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002200 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002201 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002202
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002203 if (rSubmixModule == 0) {
2204 for (size_t j = 0; i < mHwModules.size(); j++) {
2205 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2206 && mHwModules[j]->mHandle != 0) {
2207 rSubmixModule = mHwModules[j];
2208 break;
2209 }
2210 }
2211 }
2212 if (rSubmixModule == 0) {
2213 res = INVALID_OPERATION;
2214 continue;
2215 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002216
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002217 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002218
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002219 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2220 res = INVALID_OPERATION;
2221 continue;
2222 }
2223
2224 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2225 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2226 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2227 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2228 address.string(), "remote-submix");
2229 }
2230 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2231 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2232 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2233 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2234 address.string(), "remote-submix");
2235 }
2236 rSubmixModule->removeOutputProfile(address);
2237 rSubmixModule->removeInputProfile(address);
2238
2239 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2240 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2241 res = INVALID_OPERATION;
2242 continue;
2243 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002244 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002245 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002246 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002247}
2248
Eric Laurente552edb2014-03-10 17:42:56 -07002249
Eric Laurente0720872014-03-11 09:30:41 -07002250status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002251{
2252 const size_t SIZE = 256;
2253 char buffer[SIZE];
2254 String8 result;
2255
2256 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2257 result.append(buffer);
2258
Eric Laurent87ffa392015-05-22 10:32:38 -07002259 snprintf(buffer, SIZE, " Primary Output: %d\n",
2260 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002261 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002262 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002263 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002264 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002265 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002266 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002267 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002268 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002269 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002270 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002271 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002272 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002273 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002274 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002275 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002276 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002277 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002278 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2279 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2280 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002281 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2282 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002283 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2284 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002285
François Gaffie2110e042015-03-24 08:41:51 +01002286 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002287
François Gaffie112b0af2015-11-19 16:13:25 +01002288 mAvailableOutputDevices.dump(fd, String8("Available output"));
2289 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002290 mHwModules.dump(fd);
2291 mOutputs.dump(fd);
2292 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002293 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002294 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002295 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002296
2297 return NO_ERROR;
2298}
2299
2300// This function checks for the parameters which can be offloaded.
2301// This can be enhanced depending on the capability of the DSP and policy
2302// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002303bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002304{
2305 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002306 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002307 offloadInfo.sample_rate, offloadInfo.channel_mask,
2308 offloadInfo.format,
2309 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2310 offloadInfo.has_video);
2311
Andy Hung2ddee192015-12-18 17:34:44 -08002312 if (mMasterMono) {
2313 return false; // no offloading if mono is set.
2314 }
2315
Eric Laurente552edb2014-03-10 17:42:56 -07002316 // Check if offload has been disabled
2317 char propValue[PROPERTY_VALUE_MAX];
2318 if (property_get("audio.offload.disable", propValue, "0")) {
2319 if (atoi(propValue) != 0) {
2320 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2321 return false;
2322 }
2323 }
2324
2325 // Check if stream type is music, then only allow offload as of now.
2326 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2327 {
2328 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2329 return false;
2330 }
2331
2332 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002333 const bool allowOffloadWithVideo =
2334 property_get_bool("audio.offload.video", false /* default_value */);
2335 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002336 ALOGV("isOffloadSupported: has_video == true, returning false");
2337 return false;
2338 }
2339
2340 //If duration is less than minimum value defined in property, return false
2341 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2342 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2343 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2344 return false;
2345 }
2346 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2347 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2348 return false;
2349 }
2350
2351 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2352 // creating an offloaded track and tearing it down immediately after start when audioflinger
2353 // detects there is an active non offloadable effect.
2354 // FIXME: We should check the audio session here but we do not have it in this context.
2355 // This may prevent offloading in rare situations where effects are left active by apps
2356 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002357 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002358 return false;
2359 }
2360
2361 // See if there is a profile to support this.
2362 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002363 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002364 offloadInfo.sample_rate,
2365 offloadInfo.format,
2366 offloadInfo.channel_mask,
2367 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002368 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2369 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002370}
2371
Eric Laurent6a94d692014-05-20 11:18:06 -07002372status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2373 audio_port_type_t type,
2374 unsigned int *num_ports,
2375 struct audio_port *ports,
2376 unsigned int *generation)
2377{
2378 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2379 generation == NULL) {
2380 return BAD_VALUE;
2381 }
2382 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2383 if (ports == NULL) {
2384 *num_ports = 0;
2385 }
2386
2387 size_t portsWritten = 0;
2388 size_t portsMax = *num_ports;
2389 *num_ports = 0;
2390 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002391 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2392 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002393 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002394 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2395 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2396 continue;
2397 }
2398 if (portsWritten < portsMax) {
2399 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2400 }
2401 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002402 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002403 }
2404 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002405 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2406 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2407 continue;
2408 }
2409 if (portsWritten < portsMax) {
2410 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2411 }
2412 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002413 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002414 }
2415 }
2416 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2417 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2418 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2419 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2420 }
2421 *num_ports += mInputs.size();
2422 }
2423 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002424 size_t numOutputs = 0;
2425 for (size_t i = 0; i < mOutputs.size(); i++) {
2426 if (!mOutputs[i]->isDuplicated()) {
2427 numOutputs++;
2428 if (portsWritten < portsMax) {
2429 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2430 }
2431 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002432 }
Eric Laurent84c70242014-06-23 08:46:27 -07002433 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002434 }
2435 }
2436 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002437 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002438 return NO_ERROR;
2439}
2440
2441status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2442{
2443 return NO_ERROR;
2444}
2445
Eric Laurent6a94d692014-05-20 11:18:06 -07002446status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2447 audio_patch_handle_t *handle,
2448 uid_t uid)
2449{
2450 ALOGV("createAudioPatch()");
2451
2452 if (handle == NULL || patch == NULL) {
2453 return BAD_VALUE;
2454 }
2455 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2456
Eric Laurent874c42872014-08-08 15:13:39 -07002457 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2458 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2459 return BAD_VALUE;
2460 }
2461 // only one source per audio patch supported for now
2462 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002463 return INVALID_OPERATION;
2464 }
Eric Laurent874c42872014-08-08 15:13:39 -07002465
2466 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002467 return INVALID_OPERATION;
2468 }
Eric Laurent874c42872014-08-08 15:13:39 -07002469 for (size_t i = 0; i < patch->num_sinks; i++) {
2470 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2471 return INVALID_OPERATION;
2472 }
2473 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002474
2475 sp<AudioPatch> patchDesc;
2476 ssize_t index = mAudioPatches.indexOfKey(*handle);
2477
Eric Laurent6a94d692014-05-20 11:18:06 -07002478 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2479 patch->sources[0].role,
2480 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002481#if LOG_NDEBUG == 0
2482 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002483 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002484 patch->sinks[i].role,
2485 patch->sinks[i].type);
2486 }
2487#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002488
2489 if (index >= 0) {
2490 patchDesc = mAudioPatches.valueAt(index);
2491 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2492 mUidCached, patchDesc->mUid, uid);
2493 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2494 return INVALID_OPERATION;
2495 }
2496 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002497 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002498 }
2499
2500 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002501 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002502 if (outputDesc == NULL) {
2503 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2504 return BAD_VALUE;
2505 }
Eric Laurent84c70242014-06-23 08:46:27 -07002506 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2507 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002508 if (patchDesc != 0) {
2509 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2510 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2511 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2512 return BAD_VALUE;
2513 }
2514 }
Eric Laurent874c42872014-08-08 15:13:39 -07002515 DeviceVector devices;
2516 for (size_t i = 0; i < patch->num_sinks; i++) {
2517 // Only support mix to devices connection
2518 // TODO add support for mix to mix connection
2519 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2520 ALOGV("createAudioPatch() source mix but sink is not a device");
2521 return INVALID_OPERATION;
2522 }
2523 sp<DeviceDescriptor> devDesc =
2524 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2525 if (devDesc == 0) {
2526 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2527 return BAD_VALUE;
2528 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002529
François Gaffie53615e22015-03-19 09:24:12 +01002530 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002532 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002533 NULL, // updatedSamplingRate
2534 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002535 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002536 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002537 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002538 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002539 ALOGV("createAudioPatch() profile not supported for device %08x",
2540 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002541 return INVALID_OPERATION;
2542 }
2543 devices.add(devDesc);
2544 }
2545 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 return INVALID_OPERATION;
2547 }
Eric Laurent874c42872014-08-08 15:13:39 -07002548
Eric Laurent6a94d692014-05-20 11:18:06 -07002549 // TODO: reconfigure output format and channels here
2550 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002551 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002552 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002553 index = mAudioPatches.indexOfKey(*handle);
2554 if (index >= 0) {
2555 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2556 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2557 }
2558 patchDesc = mAudioPatches.valueAt(index);
2559 patchDesc->mUid = uid;
2560 ALOGV("createAudioPatch() success");
2561 } else {
2562 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2563 return INVALID_OPERATION;
2564 }
2565 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2566 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2567 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002568 // only one sink supported when connecting an input device to a mix
2569 if (patch->num_sinks > 1) {
2570 return INVALID_OPERATION;
2571 }
François Gaffie53615e22015-03-19 09:24:12 +01002572 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002573 if (inputDesc == NULL) {
2574 return BAD_VALUE;
2575 }
2576 if (patchDesc != 0) {
2577 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2578 return BAD_VALUE;
2579 }
2580 }
2581 sp<DeviceDescriptor> devDesc =
2582 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2583 if (devDesc == 0) {
2584 return BAD_VALUE;
2585 }
2586
François Gaffie53615e22015-03-19 09:24:12 +01002587 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002588 devDesc->mAddress,
2589 patch->sinks[0].sample_rate,
2590 NULL, /*updatedSampleRate*/
2591 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002592 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002593 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002594 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002595 // FIXME for the parameter type,
2596 // and the NONE
2597 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002598 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002599 return INVALID_OPERATION;
2600 }
2601 // TODO: reconfigure output format and channels here
2602 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002603 devDesc->type(), inputDesc->mIoHandle);
2604 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002605 index = mAudioPatches.indexOfKey(*handle);
2606 if (index >= 0) {
2607 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2608 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2609 }
2610 patchDesc = mAudioPatches.valueAt(index);
2611 patchDesc->mUid = uid;
2612 ALOGV("createAudioPatch() success");
2613 } else {
2614 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2615 return INVALID_OPERATION;
2616 }
2617 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2618 // device to device connection
2619 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002620 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002621 return BAD_VALUE;
2622 }
2623 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002624 sp<DeviceDescriptor> srcDeviceDesc =
2625 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002626 if (srcDeviceDesc == 0) {
2627 return BAD_VALUE;
2628 }
Eric Laurent874c42872014-08-08 15:13:39 -07002629
Eric Laurent6a94d692014-05-20 11:18:06 -07002630 //update source and sink with our own data as the data passed in the patch may
2631 // be incomplete.
2632 struct audio_patch newPatch = *patch;
2633 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002634
Eric Laurent874c42872014-08-08 15:13:39 -07002635 for (size_t i = 0; i < patch->num_sinks; i++) {
2636 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2637 ALOGV("createAudioPatch() source device but one sink is not a device");
2638 return INVALID_OPERATION;
2639 }
2640
2641 sp<DeviceDescriptor> sinkDeviceDesc =
2642 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2643 if (sinkDeviceDesc == 0) {
2644 return BAD_VALUE;
2645 }
2646 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2647
Eric Laurent3bcf8592015-04-03 12:13:24 -07002648 // create a software bridge in PatchPanel if:
2649 // - source and sink devices are on differnt HW modules OR
2650 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002651 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002652 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002653 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002654 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002655 return INVALID_OPERATION;
2656 }
Eric Laurent874c42872014-08-08 15:13:39 -07002657 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002658 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002659 // if the sink device is reachable via an opened output stream, request to go via
2660 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002661 audio_io_handle_t output = selectOutput(outputs,
2662 AUDIO_OUTPUT_FLAG_NONE,
2663 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002664 if (output != AUDIO_IO_HANDLE_NONE) {
2665 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2666 if (outputDesc->isDuplicated()) {
2667 return INVALID_OPERATION;
2668 }
2669 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002670 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002671 newPatch.num_sources = 2;
2672 }
Eric Laurent83b88082014-06-20 18:31:16 -07002673 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002674 }
2675 // TODO: check from routing capabilities in config file and other conflicting patches
2676
2677 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2678 if (index >= 0) {
2679 afPatchHandle = patchDesc->mAfPatchHandle;
2680 }
2681
2682 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2683 &afPatchHandle,
2684 0);
2685 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2686 status, afPatchHandle);
2687 if (status == NO_ERROR) {
2688 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002689 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002690 addAudioPatch(patchDesc->mHandle, patchDesc);
2691 } else {
2692 patchDesc->mPatch = newPatch;
2693 }
2694 patchDesc->mAfPatchHandle = afPatchHandle;
2695 *handle = patchDesc->mHandle;
2696 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002697 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002698 } else {
2699 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2700 status);
2701 return INVALID_OPERATION;
2702 }
2703 } else {
2704 return BAD_VALUE;
2705 }
2706 } else {
2707 return BAD_VALUE;
2708 }
2709 return NO_ERROR;
2710}
2711
2712status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2713 uid_t uid)
2714{
2715 ALOGV("releaseAudioPatch() patch %d", handle);
2716
2717 ssize_t index = mAudioPatches.indexOfKey(handle);
2718
2719 if (index < 0) {
2720 return BAD_VALUE;
2721 }
2722 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2723 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2724 mUidCached, patchDesc->mUid, uid);
2725 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2726 return INVALID_OPERATION;
2727 }
2728
2729 struct audio_patch *patch = &patchDesc->mPatch;
2730 patchDesc->mUid = mUidCached;
2731 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002732 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002733 if (outputDesc == NULL) {
2734 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2735 return BAD_VALUE;
2736 }
2737
Eric Laurentc75307b2015-03-17 15:29:32 -07002738 setOutputDevice(outputDesc,
2739 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002740 true,
2741 0,
2742 NULL);
2743 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2744 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002745 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002746 if (inputDesc == NULL) {
2747 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2748 return BAD_VALUE;
2749 }
2750 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002751 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 true,
2753 NULL);
2754 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002755 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2756 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2757 status, patchDesc->mAfPatchHandle);
2758 removeAudioPatch(patchDesc->mHandle);
2759 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002760 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002761 } else {
2762 return BAD_VALUE;
2763 }
2764 } else {
2765 return BAD_VALUE;
2766 }
2767 return NO_ERROR;
2768}
2769
2770status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2771 struct audio_patch *patches,
2772 unsigned int *generation)
2773{
François Gaffie53615e22015-03-19 09:24:12 +01002774 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002775 return BAD_VALUE;
2776 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002777 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002778 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002779}
2780
Eric Laurente1715a42014-05-20 11:30:42 -07002781status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002782{
Eric Laurente1715a42014-05-20 11:30:42 -07002783 ALOGV("setAudioPortConfig()");
2784
2785 if (config == NULL) {
2786 return BAD_VALUE;
2787 }
2788 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2789 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002790 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2791 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002792 }
2793
Eric Laurenta121f902014-06-03 13:32:54 -07002794 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002795 if (config->type == AUDIO_PORT_TYPE_MIX) {
2796 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002797 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002798 if (outputDesc == NULL) {
2799 return BAD_VALUE;
2800 }
Eric Laurent84c70242014-06-23 08:46:27 -07002801 ALOG_ASSERT(!outputDesc->isDuplicated(),
2802 "setAudioPortConfig() called on duplicated output %d",
2803 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002804 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002805 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002806 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002807 if (inputDesc == NULL) {
2808 return BAD_VALUE;
2809 }
Eric Laurenta121f902014-06-03 13:32:54 -07002810 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002811 } else {
2812 return BAD_VALUE;
2813 }
2814 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2815 sp<DeviceDescriptor> deviceDesc;
2816 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2817 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2818 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2819 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2820 } else {
2821 return BAD_VALUE;
2822 }
2823 if (deviceDesc == NULL) {
2824 return BAD_VALUE;
2825 }
Eric Laurenta121f902014-06-03 13:32:54 -07002826 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002827 } else {
2828 return BAD_VALUE;
2829 }
2830
Eric Laurenta121f902014-06-03 13:32:54 -07002831 struct audio_port_config backupConfig;
2832 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2833 if (status == NO_ERROR) {
2834 struct audio_port_config newConfig;
2835 audioPortConfig->toAudioPortConfig(&newConfig, config);
2836 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002837 }
Eric Laurenta121f902014-06-03 13:32:54 -07002838 if (status != NO_ERROR) {
2839 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002840 }
Eric Laurente1715a42014-05-20 11:30:42 -07002841
2842 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002843}
2844
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002845void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2846{
Eric Laurentd60560a2015-04-10 11:31:20 -07002847 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002848 clearAudioPatches(uid);
2849 clearSessionRoutes(uid);
2850}
2851
Eric Laurent6a94d692014-05-20 11:18:06 -07002852void AudioPolicyManager::clearAudioPatches(uid_t uid)
2853{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002854 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002855 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2856 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002857 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 }
2859 }
2860}
2861
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002862void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2863 audio_io_handle_t ouptutToSkip)
2864{
2865 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2866 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2867 for (size_t j = 0; j < mOutputs.size(); j++) {
2868 if (mOutputs.keyAt(j) == ouptutToSkip) {
2869 continue;
2870 }
2871 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2872 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2873 continue;
2874 }
2875 // If the default device for this strategy is on another output mix,
2876 // invalidate all tracks in this strategy to force re connection.
2877 // Otherwise select new device on the output mix.
2878 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002879 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002880 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2881 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2882 }
2883 }
2884 } else {
2885 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2886 setOutputDevice(outputDesc, newDevice, false);
2887 }
2888 }
2889}
2890
2891void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2892{
2893 // remove output routes associated with this uid
2894 SortedVector<routing_strategy> affectedStrategies;
2895 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2896 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2897 if (route->mUid == uid) {
2898 mOutputRoutes.removeItemsAt(i);
2899 if (route->mDeviceDescriptor != 0) {
2900 affectedStrategies.add(getStrategy(route->mStreamType));
2901 }
2902 }
2903 }
2904 // reroute outputs if necessary
2905 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2906 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2907 }
2908
2909 // remove input routes associated with this uid
2910 SortedVector<audio_source_t> affectedSources;
2911 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2912 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2913 if (route->mUid == uid) {
2914 mInputRoutes.removeItemsAt(i);
2915 if (route->mDeviceDescriptor != 0) {
2916 affectedSources.add(route->mSource);
2917 }
2918 }
2919 }
2920 // reroute inputs if necessary
2921 SortedVector<audio_io_handle_t> inputsToClose;
2922 for (size_t i = 0; i < mInputs.size(); i++) {
2923 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002924 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002925 inputsToClose.add(inputDesc->mIoHandle);
2926 }
2927 }
2928 for (size_t i = 0; i < inputsToClose.size(); i++) {
2929 closeInput(inputsToClose[i]);
2930 }
2931}
2932
Eric Laurentd60560a2015-04-10 11:31:20 -07002933void AudioPolicyManager::clearAudioSources(uid_t uid)
2934{
2935 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2936 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2937 if (sourceDesc->mUid == uid) {
2938 stopAudioSource(mAudioSources.keyAt(i));
2939 }
2940 }
2941}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002942
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002943status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2944 audio_io_handle_t *ioHandle,
2945 audio_devices_t *device)
2946{
Glenn Kasteneeecb982016-02-26 10:44:04 -08002947 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2948 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002949 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002950
François Gaffiedf372692015-03-19 10:43:27 +01002951 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002952}
2953
Eric Laurentd60560a2015-04-10 11:31:20 -07002954status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2955 const audio_attributes_t *attributes,
2956 audio_io_handle_t *handle,
2957 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002958{
Eric Laurentd60560a2015-04-10 11:31:20 -07002959 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2960 if (source == NULL || attributes == NULL || handle == NULL) {
2961 return BAD_VALUE;
2962 }
2963
2964 *handle = AUDIO_IO_HANDLE_NONE;
2965
2966 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2967 source->type != AUDIO_PORT_TYPE_DEVICE) {
2968 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2969 return INVALID_OPERATION;
2970 }
2971
2972 sp<DeviceDescriptor> srcDeviceDesc =
2973 mAvailableInputDevices.getDevice(source->ext.device.type,
2974 String8(source->ext.device.address));
2975 if (srcDeviceDesc == 0) {
2976 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2977 return BAD_VALUE;
2978 }
2979 sp<AudioSourceDescriptor> sourceDesc =
2980 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2981
2982 struct audio_patch dummyPatch;
2983 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2984 sourceDesc->mPatchDesc = patchDesc;
2985
2986 status_t status = connectAudioSource(sourceDesc);
2987 if (status == NO_ERROR) {
2988 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2989 *handle = sourceDesc->getHandle();
2990 }
2991 return status;
2992}
2993
2994status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2995{
2996 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2997
2998 // make sure we only have one patch per source.
2999 disconnectAudioSource(sourceDesc);
3000
3001 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003002 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003003 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3004
3005 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3006 sp<DeviceDescriptor> sinkDeviceDesc =
3007 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3008
3009 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3010 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3011
3012 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3013 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003014 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003015 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3016 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3017 // create patch between src device and output device
3018 // create Hwoutput and add to mHwOutputs
3019 } else {
3020 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3021 audio_io_handle_t output =
3022 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3023 if (output == AUDIO_IO_HANDLE_NONE) {
3024 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3025 return INVALID_OPERATION;
3026 }
3027 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3028 if (outputDesc->isDuplicated()) {
3029 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3030 return INVALID_OPERATION;
3031 }
3032 // create a special patch with no sink and two sources:
3033 // - the second source indicates to PatchPanel through which output mix this patch should
3034 // be connected as well as the stream type for volume control
3035 // - the sink is defined by whatever output device is currently selected for the output
3036 // though which this patch is routed.
3037 patch->num_sinks = 0;
3038 patch->num_sources = 2;
3039 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3040 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3041 patch->sources[1].ext.mix.usecase.stream = stream;
3042 status_t status = mpClientInterface->createAudioPatch(patch,
3043 &afPatchHandle,
3044 0);
3045 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3046 status, afPatchHandle);
3047 if (status != NO_ERROR) {
3048 ALOGW("%s patch panel could not connect device patch, error %d",
3049 __FUNCTION__, status);
3050 return INVALID_OPERATION;
3051 }
3052 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003053 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003054
3055 if (status != NO_ERROR) {
3056 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3057 return status;
3058 }
3059 sourceDesc->mSwOutput = outputDesc;
3060 if (delayMs != 0) {
3061 usleep(delayMs * 1000);
3062 }
3063 }
3064
3065 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3066 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3067
3068 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003069}
3070
Eric Laurent493404d2015-04-21 15:07:36 -07003071status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003072{
Eric Laurentd60560a2015-04-10 11:31:20 -07003073 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3074 ALOGV("%s handle %d", __FUNCTION__, handle);
3075 if (sourceDesc == 0) {
3076 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3077 return BAD_VALUE;
3078 }
3079 status_t status = disconnectAudioSource(sourceDesc);
3080
3081 mAudioSources.removeItem(handle);
3082 return status;
3083}
3084
Andy Hung2ddee192015-12-18 17:34:44 -08003085status_t AudioPolicyManager::setMasterMono(bool mono)
3086{
3087 if (mMasterMono == mono) {
3088 return NO_ERROR;
3089 }
3090 mMasterMono = mono;
3091 // if enabling mono we close all offloaded devices, which will invalidate the
3092 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3093 // for recreating the new AudioTrack as non-offloaded PCM.
3094 //
3095 // If disabling mono, we leave all tracks as is: we don't know which clients
3096 // and tracks are able to be recreated as offloaded. The next "song" should
3097 // play back offloaded.
3098 if (mMasterMono) {
3099 Vector<audio_io_handle_t> offloaded;
3100 for (size_t i = 0; i < mOutputs.size(); ++i) {
3101 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3102 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3103 offloaded.push(desc->mIoHandle);
3104 }
3105 }
3106 for (size_t i = 0; i < offloaded.size(); ++i) {
3107 closeOutput(offloaded[i]);
3108 }
3109 }
3110 // update master mono for all remaining outputs
3111 for (size_t i = 0; i < mOutputs.size(); ++i) {
3112 updateMono(mOutputs.keyAt(i));
3113 }
3114 return NO_ERROR;
3115}
3116
3117status_t AudioPolicyManager::getMasterMono(bool *mono)
3118{
3119 *mono = mMasterMono;
3120 return NO_ERROR;
3121}
3122
Eric Laurentd60560a2015-04-10 11:31:20 -07003123status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3124{
3125 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3126
3127 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3128 if (patchDesc == 0) {
3129 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3130 sourceDesc->mPatchDesc->mHandle);
3131 return BAD_VALUE;
3132 }
3133 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3134
Eric Laurent28d09f02016-03-08 10:43:05 -08003135 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003136 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3137 if (swOutputDesc != 0) {
3138 stopSource(swOutputDesc, stream, false);
3139 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3140 } else {
3141 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3142 if (hwOutputDesc != 0) {
3143 // release patch between src device and output device
3144 // close Hwoutput and remove from mHwOutputs
3145 } else {
3146 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3147 }
3148 }
3149 return NO_ERROR;
3150}
3151
3152sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3153 audio_io_handle_t output, routing_strategy strategy)
3154{
3155 sp<AudioSourceDescriptor> source;
3156 for (size_t i = 0; i < mAudioSources.size(); i++) {
3157 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3158 routing_strategy sourceStrategy =
3159 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3160 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3161 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3162 source = sourceDesc;
3163 break;
3164 }
3165 }
3166 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003167}
3168
Eric Laurente552edb2014-03-10 17:42:56 -07003169// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003170// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003171// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003172uint32_t AudioPolicyManager::nextAudioPortGeneration()
3173{
3174 return android_atomic_inc(&mAudioPortGeneration);
3175}
3176
Eric Laurente0720872014-03-11 09:30:41 -07003177AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003178 :
3179#ifdef AUDIO_POLICY_TEST
3180 Thread(false),
3181#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003182 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003183 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003184 mAudioPortGeneration(1),
3185 mBeaconMuteRefCount(0),
3186 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003187 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003188 mTtsOutputAvailable(false),
3189 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003190{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003191 mUidCached = getuid();
3192 mpClientInterface = clientInterface;
3193
3194 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3195 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3196 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3197 bool speakerDrcEnabled = false;
3198
3199#ifdef USE_XML_AUDIO_POLICY_CONF
3200 mVolumeCurves = new VolumeCurvesCollection();
3201 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3202 mDefaultOutputDevice, speakerDrcEnabled,
3203 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3204 PolicySerializer serializer;
3205 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3206#else
3207 mVolumeCurves = new StreamDescriptorCollection();
3208 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3209 mDefaultOutputDevice, speakerDrcEnabled);
3210 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3211 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3212#endif
3213 ALOGE("could not load audio policy configuration file, setting defaults");
3214 config.setDefault();
3215 }
3216 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3217 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3218
3219 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003220 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3221 if (!engineInstance) {
3222 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3223 return;
3224 }
3225 // Retrieve the Policy Manager Interface
3226 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3227 if (mEngine == NULL) {
3228 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3229 return;
3230 }
3231 mEngine->setObserver(this);
3232 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003233 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003234 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3235
Eric Laurent3a4311c2014-03-17 12:00:47 -07003236 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003237 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003238 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3239 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003240 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003241 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003242 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003243 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003244 continue;
3245 }
3246 // open all output streams needed to access attached devices
3247 // except for direct output streams that are only opened when they are actually
3248 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003249 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003250 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3251 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003252 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003253
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003254 if (!outProfile->hasSupportedDevices()) {
3255 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003256 continue;
3257 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003258 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003259 mTtsOutputAvailable = true;
3260 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003261
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003262 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003263 continue;
3264 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003265 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003266 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3267 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003268 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003269 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003270 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003271 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003272 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003273 if ((profileType & outputDeviceTypes) == 0) {
3274 continue;
3275 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003276 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3277 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003278 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3279 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3280 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3281 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003282
3283 outputDesc->mDevice = profileType;
3284 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3285 config.sample_rate = outputDesc->mSamplingRate;
3286 config.channel_mask = outputDesc->mChannelMask;
3287 config.format = outputDesc->mFormat;
3288 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003289 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003290 &output,
3291 &config,
3292 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003293 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003294 &outputDesc->mLatency,
3295 outputDesc->mFlags);
3296
3297 if (status != NO_ERROR) {
3298 ALOGW("Cannot open output stream for device %08x on hw module %s",
3299 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003300 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003301 } else {
3302 outputDesc->mSamplingRate = config.sample_rate;
3303 outputDesc->mChannelMask = config.channel_mask;
3304 outputDesc->mFormat = config.format;
3305
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003306 for (size_t k = 0; k < supportedDevices.size(); k++) {
3307 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003308 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003309 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3310 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003311 }
3312 }
3313 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003314 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003315 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003316 }
3317 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003318 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003319 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003320 true,
3321 0,
3322 NULL,
3323 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003324 }
Eric Laurente552edb2014-03-10 17:42:56 -07003325 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003326 // open input streams needed to access attached devices to validate
3327 // mAvailableInputDevices list
3328 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3329 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003330 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003331
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003332 if (!inProfile->hasSupportedDevices()) {
3333 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003334 continue;
3335 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003336 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003337 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003338 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3339
Eric Laurentd78f1532014-09-16 16:38:20 -07003340 if ((profileType & inputDeviceTypes) == 0) {
3341 continue;
3342 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003343 sp<AudioInputDescriptor> inputDesc =
3344 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003345
Eric Laurentd78f1532014-09-16 16:38:20 -07003346 inputDesc->mDevice = profileType;
3347
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003348 // find the address
3349 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3350 // the inputs vector must be of size 1, but we don't want to crash here
3351 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3352 : String8("");
3353 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3354 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3355
Eric Laurentd78f1532014-09-16 16:38:20 -07003356 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3357 config.sample_rate = inputDesc->mSamplingRate;
3358 config.channel_mask = inputDesc->mChannelMask;
3359 config.format = inputDesc->mFormat;
3360 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003361 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003362 &input,
3363 &config,
3364 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003365 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003366 AUDIO_SOURCE_MIC,
3367 AUDIO_INPUT_FLAG_NONE);
3368
3369 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003370 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3371 for (size_t k = 0; k < supportedDevices.size(); k++) {
3372 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003373 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003374 if (index >= 0) {
3375 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3376 if (!devDesc->isAttached()) {
3377 devDesc->attach(mHwModules[i]);
3378 devDesc->importAudioPort(inProfile);
3379 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003380 }
3381 }
3382 mpClientInterface->closeInput(input);
3383 } else {
3384 ALOGW("Cannot open input stream for device %08x on hw module %s",
3385 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003386 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003387 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003388 }
3389 }
3390 // make sure all attached devices have been allocated a unique ID
3391 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003392 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003393 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003394 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3395 continue;
3396 }
François Gaffie2110e042015-03-24 08:41:51 +01003397 // The device is now validated and can be appended to the available devices of the engine
3398 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3399 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003400 i++;
3401 }
3402 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003403 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003404 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003405 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3406 continue;
3407 }
François Gaffie2110e042015-03-24 08:41:51 +01003408 // The device is now validated and can be appended to the available devices of the engine
3409 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3410 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003411 i++;
3412 }
3413 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003414 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003415 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 }
Eric Laurente552edb2014-03-10 17:42:56 -07003417
3418 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3419
3420 updateDevicesAndOutputs();
3421
3422#ifdef AUDIO_POLICY_TEST
3423 if (mPrimaryOutput != 0) {
3424 AudioParameter outputCmd = AudioParameter();
3425 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003426 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003427
3428 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3429 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003430 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3431 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003432 mTestLatencyMs = 0;
3433 mCurOutput = 0;
3434 mDirectOutput = false;
3435 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3436 mTestOutputs[i] = 0;
3437 }
3438
3439 const size_t SIZE = 256;
3440 char buffer[SIZE];
3441 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3442 run(buffer, ANDROID_PRIORITY_AUDIO);
3443 }
3444#endif //AUDIO_POLICY_TEST
3445}
3446
Eric Laurente0720872014-03-11 09:30:41 -07003447AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003448{
3449#ifdef AUDIO_POLICY_TEST
3450 exit();
3451#endif //AUDIO_POLICY_TEST
3452 for (size_t i = 0; i < mOutputs.size(); i++) {
3453 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003454 }
3455 for (size_t i = 0; i < mInputs.size(); i++) {
3456 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003457 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003458 mAvailableOutputDevices.clear();
3459 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003460 mOutputs.clear();
3461 mInputs.clear();
3462 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003463}
3464
Eric Laurente0720872014-03-11 09:30:41 -07003465status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003466{
Eric Laurent87ffa392015-05-22 10:32:38 -07003467 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003468}
3469
3470#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003471bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003472{
3473 ALOGV("entering threadLoop()");
3474 while (!exitPending())
3475 {
3476 String8 command;
3477 int valueInt;
3478 String8 value;
3479
3480 Mutex::Autolock _l(mLock);
3481 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3482
3483 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3484 AudioParameter param = AudioParameter(command);
3485
3486 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3487 valueInt != 0) {
3488 ALOGV("Test command %s received", command.string());
3489 String8 target;
3490 if (param.get(String8("target"), target) != NO_ERROR) {
3491 target = "Manager";
3492 }
3493 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3494 param.remove(String8("test_cmd_policy_output"));
3495 mCurOutput = valueInt;
3496 }
3497 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3498 param.remove(String8("test_cmd_policy_direct"));
3499 if (value == "false") {
3500 mDirectOutput = false;
3501 } else if (value == "true") {
3502 mDirectOutput = true;
3503 }
3504 }
3505 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3506 param.remove(String8("test_cmd_policy_input"));
3507 mTestInput = valueInt;
3508 }
3509
3510 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3511 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003512 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003513 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003514 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003515 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003516 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003517 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003518 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003520 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003521 if (target == "Manager") {
3522 mTestFormat = format;
3523 } else if (mTestOutputs[mCurOutput] != 0) {
3524 AudioParameter outputParam = AudioParameter();
3525 outputParam.addInt(String8("format"), format);
3526 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3527 }
3528 }
3529 }
3530 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3531 param.remove(String8("test_cmd_policy_channels"));
3532 int channels = 0;
3533
3534 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003535 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003536 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003537 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 }
3539 if (channels != 0) {
3540 if (target == "Manager") {
3541 mTestChannels = channels;
3542 } else if (mTestOutputs[mCurOutput] != 0) {
3543 AudioParameter outputParam = AudioParameter();
3544 outputParam.addInt(String8("channels"), channels);
3545 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3546 }
3547 }
3548 }
3549 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3550 param.remove(String8("test_cmd_policy_sampleRate"));
3551 if (valueInt >= 0 && valueInt <= 96000) {
3552 int samplingRate = valueInt;
3553 if (target == "Manager") {
3554 mTestSamplingRate = samplingRate;
3555 } else if (mTestOutputs[mCurOutput] != 0) {
3556 AudioParameter outputParam = AudioParameter();
3557 outputParam.addInt(String8("sampling_rate"), samplingRate);
3558 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3559 }
3560 }
3561 }
3562
3563 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3564 param.remove(String8("test_cmd_policy_reopen"));
3565
Eric Laurentc75307b2015-03-17 15:29:32 -07003566 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003567
Eric Laurentc75307b2015-03-17 15:29:32 -07003568 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003569
Eric Laurentc75307b2015-03-17 15:29:32 -07003570 removeOutput(mPrimaryOutput->mIoHandle);
3571 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3572 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003573 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003574 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3575 config.sample_rate = outputDesc->mSamplingRate;
3576 config.channel_mask = outputDesc->mChannelMask;
3577 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003578 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003579 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003580 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003581 &config,
3582 &outputDesc->mDevice,
3583 String8(""),
3584 &outputDesc->mLatency,
3585 outputDesc->mFlags);
3586 if (status != NO_ERROR) {
3587 ALOGE("Failed to reopen hardware output stream, "
3588 "samplingRate: %d, format %d, channels %d",
3589 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003590 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003591 outputDesc->mSamplingRate = config.sample_rate;
3592 outputDesc->mChannelMask = config.channel_mask;
3593 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003594 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003595 AudioParameter outputCmd = AudioParameter();
3596 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003597 mpClientInterface->setParameters(handle, outputCmd.toString());
3598 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003599 }
3600 }
3601
3602
3603 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3604 }
3605 }
3606 return false;
3607}
3608
Eric Laurente0720872014-03-11 09:30:41 -07003609void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003610{
3611 {
3612 AutoMutex _l(mLock);
3613 requestExit();
3614 mWaitWorkCV.signal();
3615 }
3616 requestExitAndWait();
3617}
3618
Eric Laurente0720872014-03-11 09:30:41 -07003619int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003620{
3621 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3622 if (output == mTestOutputs[i]) return i;
3623 }
3624 return 0;
3625}
3626#endif //AUDIO_POLICY_TEST
3627
3628// ---
3629
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003630void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003631{
François Gaffie98cc1912015-03-18 17:52:40 +01003632 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003633 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003634 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003635 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003636}
3637
François Gaffie53615e22015-03-19 09:24:12 +01003638void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3639{
3640 mOutputs.removeItem(output);
3641}
3642
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003643void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003644{
François Gaffie98cc1912015-03-18 17:52:40 +01003645 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003646 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003647 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003648}
Eric Laurente552edb2014-03-10 17:42:56 -07003649
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003650void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003651 const audio_devices_t device /*in*/,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003652 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003653 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003654 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003655 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003656 if (devDesc != 0) {
3657 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3658 desc->mIoHandle, address.string());
3659 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003660 }
3661}
3662
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003663status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003664 audio_policy_dev_state_t state,
3665 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003666 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003667{
François Gaffie53615e22015-03-19 09:24:12 +01003668 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003669 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003670
3671 if (audio_device_is_digital(device)) {
3672 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003673 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003674 }
Eric Laurente552edb2014-03-10 17:42:56 -07003675
Eric Laurent3b73df72014-03-11 09:06:29 -07003676 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003677 // first list already open outputs that can be routed to this device
3678 for (size_t i = 0; i < mOutputs.size(); i++) {
3679 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003680 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003681 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003682 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3683 outputs.add(mOutputs.keyAt(i));
3684 } else {
3685 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003686 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003687 }
Eric Laurente552edb2014-03-10 17:42:56 -07003688 }
3689 }
3690 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003691 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003692 for (size_t i = 0; i < mHwModules.size(); i++)
3693 {
3694 if (mHwModules[i]->mHandle == 0) {
3695 continue;
3696 }
3697 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3698 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003699 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003700 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003701 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003702 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003703 profiles.add(profile);
3704 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3705 }
Eric Laurente552edb2014-03-10 17:42:56 -07003706 }
3707 }
3708 }
3709
Eric Laurent7b279bb2015-12-14 10:18:23 -08003710 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003711
Eric Laurente552edb2014-03-10 17:42:56 -07003712 if (profiles.isEmpty() && outputs.isEmpty()) {
3713 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3714 return BAD_VALUE;
3715 }
3716
3717 // open outputs for matching profiles if needed. Direct outputs are also opened to
3718 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3719 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003720 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003721
3722 // nothing to do if one output is already opened for this profile
3723 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003724 for (j = 0; j < outputs.size(); j++) {
3725 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003726 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003727 // matching profile: save the sample rates, format and channel masks supported
3728 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003729 if (audio_device_is_digital(device)) {
3730 devDesc->importAudioPort(profile);
3731 }
Eric Laurente552edb2014-03-10 17:42:56 -07003732 break;
3733 }
3734 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003735 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003736 continue;
3737 }
3738
Eric Laurent83b88082014-06-20 18:31:16 -07003739 ALOGV("opening output for device %08x with params %s profile %p",
3740 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003741 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003742 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003743 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3744 config.sample_rate = desc->mSamplingRate;
3745 config.channel_mask = desc->mChannelMask;
3746 config.format = desc->mFormat;
3747 config.offload_info.sample_rate = desc->mSamplingRate;
3748 config.offload_info.channel_mask = desc->mChannelMask;
3749 config.offload_info.format = desc->mFormat;
3750 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003751 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003752 &output,
3753 &config,
3754 &desc->mDevice,
3755 address,
3756 &desc->mLatency,
3757 desc->mFlags);
3758 if (status == NO_ERROR) {
3759 desc->mSamplingRate = config.sample_rate;
3760 desc->mChannelMask = config.channel_mask;
3761 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003762
Eric Laurentd4692962014-05-05 18:13:44 -07003763 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003764 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003765 char *param = audio_device_address_to_parameter(device, address);
3766 mpClientInterface->setParameters(output, String8(param));
3767 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003768 }
Phil Burk00eeb322016-03-31 12:41:00 -07003769 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003770 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003771 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003772 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003773 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003774 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003775 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003776 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003777 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003778 config.offload_info.sample_rate = config.sample_rate;
3779 config.offload_info.channel_mask = config.channel_mask;
3780 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003781 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003782 &output,
3783 &config,
3784 &desc->mDevice,
3785 address,
3786 &desc->mLatency,
3787 desc->mFlags);
3788 if (status == NO_ERROR) {
3789 desc->mSamplingRate = config.sample_rate;
3790 desc->mChannelMask = config.channel_mask;
3791 desc->mFormat = config.format;
3792 } else {
3793 output = AUDIO_IO_HANDLE_NONE;
3794 }
Eric Laurentd4692962014-05-05 18:13:44 -07003795 }
3796
Eric Laurentcf2c0212014-07-25 16:20:43 -07003797 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003798 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003799 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003800 sp<AudioPolicyMix> policyMix;
3801 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003802 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3803 address.string());
3804 }
François Gaffie036e1e92015-03-19 10:16:24 +01003805 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003806 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003807
Eric Laurent87ffa392015-05-22 10:32:38 -07003808 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3809 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003810 // no duplicated output for direct outputs and
3811 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003812 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003813
Eric Laurentd4692962014-05-05 18:13:44 -07003814 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003815 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003816
Eric Laurentd4692962014-05-05 18:13:44 -07003817 //TODO: configure audio effect output stage here
3818
3819 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003820 duplicatedOutput =
3821 mpClientInterface->openDuplicateOutput(output,
3822 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003823 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003824 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003825 sp<SwAudioOutputDescriptor> dupOutputDesc =
3826 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3827 dupOutputDesc->mOutput1 = mPrimaryOutput;
3828 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003829 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3830 dupOutputDesc->mFormat = desc->mFormat;
3831 dupOutputDesc->mChannelMask = desc->mChannelMask;
3832 dupOutputDesc->mLatency = desc->mLatency;
3833 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003834 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003835 } else {
3836 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003837 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003838 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003839 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003840 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003841 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003842 }
Eric Laurente552edb2014-03-10 17:42:56 -07003843 }
3844 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003845 } else {
3846 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003847 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003848 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003849 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003850 profiles.removeAt(profile_index);
3851 profile_index--;
3852 } else {
3853 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003854 // Load digital format info only for digital devices
3855 if (audio_device_is_digital(device)) {
3856 devDesc->importAudioPort(profile);
3857 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003858
François Gaffie53615e22015-03-19 09:24:12 +01003859 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003860 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3861 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003862 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003863 NULL/*patch handle*/, address.string());
3864 }
Eric Laurente552edb2014-03-10 17:42:56 -07003865 ALOGV("checkOutputsForDevice(): adding output %d", output);
3866 }
3867 }
3868
3869 if (profiles.isEmpty()) {
3870 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3871 return BAD_VALUE;
3872 }
Eric Laurentd4692962014-05-05 18:13:44 -07003873 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003874 // check if one opened output is not needed any more after disconnecting one device
3875 for (size_t i = 0; i < mOutputs.size(); i++) {
3876 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003877 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003878 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003879 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003880 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003881 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003882 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003883 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3884 mOutputs.keyAt(i));
3885 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003886 }
Eric Laurente552edb2014-03-10 17:42:56 -07003887 }
3888 }
Eric Laurentd4692962014-05-05 18:13:44 -07003889 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003890 for (size_t i = 0; i < mHwModules.size(); i++)
3891 {
3892 if (mHwModules[i]->mHandle == 0) {
3893 continue;
3894 }
3895 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3896 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003897 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003898 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003899 ALOGV("checkOutputsForDevice(): "
3900 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003901 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003902 }
3903 }
3904 }
3905 }
3906 return NO_ERROR;
3907}
3908
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003909status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003910 audio_policy_dev_state_t state,
3911 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07003912 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003913{
Paul McLean9080a4c2015-06-18 08:24:02 -07003914 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003915 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003916
3917 if (audio_device_is_digital(device)) {
3918 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003919 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003920 }
3921
Eric Laurentd4692962014-05-05 18:13:44 -07003922 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3923 // first list already open inputs that can be routed to this device
3924 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3925 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003926 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003927 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3928 inputs.add(mInputs.keyAt(input_index));
3929 }
3930 }
3931
3932 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003933 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003934 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3935 {
3936 if (mHwModules[module_idx]->mHandle == 0) {
3937 continue;
3938 }
3939 for (size_t profile_index = 0;
3940 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3941 profile_index++)
3942 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003943 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3944
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003946 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003947 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003948 profiles.add(profile);
3949 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3950 profile_index, module_idx);
3951 }
Eric Laurentd4692962014-05-05 18:13:44 -07003952 }
3953 }
3954 }
3955
3956 if (profiles.isEmpty() && inputs.isEmpty()) {
3957 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3958 return BAD_VALUE;
3959 }
3960
3961 // open inputs for matching profiles if needed. Direct inputs are also opened to
3962 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3963 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3964
Eric Laurent1c333e22014-05-20 10:48:17 -07003965 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003966 // nothing to do if one input is already opened for this profile
3967 size_t input_index;
3968 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3969 desc = mInputs.valueAt(input_index);
3970 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003971 if (audio_device_is_digital(device)) {
3972 devDesc->importAudioPort(profile);
3973 }
Eric Laurentd4692962014-05-05 18:13:44 -07003974 break;
3975 }
3976 }
3977 if (input_index != mInputs.size()) {
3978 continue;
3979 }
3980
3981 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3982 desc = new AudioInputDescriptor(profile);
3983 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003984 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3985 config.sample_rate = desc->mSamplingRate;
3986 config.channel_mask = desc->mChannelMask;
3987 config.format = desc->mFormat;
3988 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003989 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003990 &input,
3991 &config,
3992 &desc->mDevice,
3993 address,
3994 AUDIO_SOURCE_MIC,
3995 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003996
Eric Laurentcf2c0212014-07-25 16:20:43 -07003997 if (status == NO_ERROR) {
3998 desc->mSamplingRate = config.sample_rate;
3999 desc->mChannelMask = config.channel_mask;
4000 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004001
Eric Laurentd4692962014-05-05 18:13:44 -07004002 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004003 char *param = audio_device_address_to_parameter(device, address);
4004 mpClientInterface->setParameters(input, String8(param));
4005 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004006 }
Phil Burk00eeb322016-03-31 12:41:00 -07004007 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004008 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004009 ALOGW("checkInputsForDevice() direct input missing param");
4010 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004011 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004012 }
4013
4014 if (input != 0) {
4015 addInput(input, desc);
4016 }
4017 } // endif input != 0
4018
Eric Laurentcf2c0212014-07-25 16:20:43 -07004019 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004020 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004021 profiles.removeAt(profile_index);
4022 profile_index--;
4023 } else {
4024 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004025 if (audio_device_is_digital(device)) {
4026 devDesc->importAudioPort(profile);
4027 }
Eric Laurentd4692962014-05-05 18:13:44 -07004028 ALOGV("checkInputsForDevice(): adding input %d", input);
4029 }
4030 } // end scan profiles
4031
4032 if (profiles.isEmpty()) {
4033 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4034 return BAD_VALUE;
4035 }
4036 } else {
4037 // Disconnect
4038 // check if one opened input is not needed any more after disconnecting one device
4039 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4040 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004041 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004042 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4043 mInputs.keyAt(input_index));
4044 inputs.add(mInputs.keyAt(input_index));
4045 }
4046 }
4047 // Clear any profiles associated with the disconnected device.
4048 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4049 if (mHwModules[module_index]->mHandle == 0) {
4050 continue;
4051 }
4052 for (size_t profile_index = 0;
4053 profile_index < mHwModules[module_index]->mInputProfiles.size();
4054 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004055 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004056 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004057 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004058 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004059 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004060 }
4061 }
4062 }
4063 } // end disconnect
4064
4065 return NO_ERROR;
4066}
4067
4068
Eric Laurente0720872014-03-11 09:30:41 -07004069void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004070{
4071 ALOGV("closeOutput(%d)", output);
4072
Eric Laurentc75307b2015-03-17 15:29:32 -07004073 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004074 if (outputDesc == NULL) {
4075 ALOGW("closeOutput() unknown output %d", output);
4076 return;
4077 }
François Gaffie036e1e92015-03-19 10:16:24 +01004078 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004079
Eric Laurente552edb2014-03-10 17:42:56 -07004080 // look for duplicated outputs connected to the output being removed.
4081 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004082 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004083 if (dupOutputDesc->isDuplicated() &&
4084 (dupOutputDesc->mOutput1 == outputDesc ||
4085 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004086 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004087 if (dupOutputDesc->mOutput1 == outputDesc) {
4088 outputDesc2 = dupOutputDesc->mOutput2;
4089 } else {
4090 outputDesc2 = dupOutputDesc->mOutput1;
4091 }
4092 // As all active tracks on duplicated output will be deleted,
4093 // and as they were also referenced on the other output, the reference
4094 // count for their stream type must be adjusted accordingly on
4095 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004096 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004097 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004098 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004099 }
4100 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4101 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4102
4103 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004104 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004105 }
4106 }
4107
Eric Laurent05b90f82014-08-27 15:32:29 -07004108 nextAudioPortGeneration();
4109
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004110 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004111 if (index >= 0) {
4112 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004113 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004114 mAudioPatches.removeItemsAt(index);
4115 mpClientInterface->onAudioPatchListUpdate();
4116 }
4117
Eric Laurente552edb2014-03-10 17:42:56 -07004118 AudioParameter param;
4119 param.add(String8("closing"), String8("true"));
4120 mpClientInterface->setParameters(output, param.toString());
4121
4122 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004123 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004124 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004125}
4126
4127void AudioPolicyManager::closeInput(audio_io_handle_t input)
4128{
4129 ALOGV("closeInput(%d)", input);
4130
4131 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4132 if (inputDesc == NULL) {
4133 ALOGW("closeInput() unknown input %d", input);
4134 return;
4135 }
4136
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004138
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004139 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004140 if (index >= 0) {
4141 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004142 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004143 mAudioPatches.removeItemsAt(index);
4144 mpClientInterface->onAudioPatchListUpdate();
4145 }
4146
4147 mpClientInterface->closeInput(input);
4148 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004149}
4150
Eric Laurentc75307b2015-03-17 15:29:32 -07004151SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4152 audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004153 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004154{
4155 SortedVector<audio_io_handle_t> outputs;
4156
4157 ALOGVV("getOutputsForDevice() device %04x", device);
4158 for (size_t i = 0; i < openOutputs.size(); i++) {
4159 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004160 i, openOutputs.valueAt(i)->isDuplicated(),
4161 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004162 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4163 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4164 outputs.add(openOutputs.keyAt(i));
4165 }
4166 }
4167 return outputs;
4168}
4169
Eric Laurente0720872014-03-11 09:30:41 -07004170bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004171 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004172{
4173 if (outputs1.size() != outputs2.size()) {
4174 return false;
4175 }
4176 for (size_t i = 0; i < outputs1.size(); i++) {
4177 if (outputs1[i] != outputs2[i]) {
4178 return false;
4179 }
4180 }
4181 return true;
4182}
4183
Eric Laurente0720872014-03-11 09:30:41 -07004184void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004185{
4186 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4187 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4188 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4189 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4190
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004191 // also take into account external policy-related changes: add all outputs which are
4192 // associated with policies in the "before" and "after" output vectors
4193 ALOGVV("checkOutputForStrategy(): policy related outputs");
4194 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004195 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004196 if (desc != 0 && desc->mPolicyMix != NULL) {
4197 srcOutputs.add(desc->mIoHandle);
4198 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4199 }
4200 }
4201 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004202 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004203 if (desc != 0 && desc->mPolicyMix != NULL) {
4204 dstOutputs.add(desc->mIoHandle);
4205 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4206 }
4207 }
4208
Eric Laurente552edb2014-03-10 17:42:56 -07004209 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4210 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4211 strategy, srcOutputs[0], dstOutputs[0]);
4212 // mute strategy while moving tracks from one output to another
4213 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004214 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004215 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004216 setStrategyMute(strategy, true, desc);
4217 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004218 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004219 sp<AudioSourceDescriptor> source =
4220 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4221 if (source != 0){
4222 connectAudioSource(source);
4223 }
Eric Laurente552edb2014-03-10 17:42:56 -07004224 }
4225
4226 // Move effects associated to this strategy from previous output to new output
4227 if (strategy == STRATEGY_MEDIA) {
4228 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4229 SortedVector<audio_io_handle_t> moved;
4230 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004231 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4232 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4233 effectDesc->mIo != fxOutput) {
4234 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4236 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004237 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004238 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004239 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004240 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004241 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004242 }
4243 }
4244 }
4245 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004246 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004247 if (getStrategy((audio_stream_type_t)i) == strategy) {
4248 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004249 }
4250 }
4251 }
4252}
4253
Eric Laurente0720872014-03-11 09:30:41 -07004254void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004255{
François Gaffie2110e042015-03-24 08:41:51 +01004256 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004257 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004259 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004260 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004261 checkOutputForStrategy(STRATEGY_SONIFICATION);
4262 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004263 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004264 checkOutputForStrategy(STRATEGY_MEDIA);
4265 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004266 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004267}
4268
Eric Laurente0720872014-03-11 09:30:41 -07004269void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004270{
François Gaffie53615e22015-03-19 09:24:12 +01004271 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004272 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004273 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004274 return;
4275 }
4276
Eric Laurent3a4311c2014-03-17 12:00:47 -07004277 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004278 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4279 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4280 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004281 // suspend A2DP output if:
4282 // (NOT already suspended) &&
4283 // ((SCO device is connected &&
4284 // (forced usage for communication || for record is SCO))) ||
4285 // (phone state is ringing || in call)
4286 //
4287 // restore A2DP output if:
4288 // (Already suspended) &&
4289 // ((SCO device is NOT connected ||
4290 // (forced usage NOT for communication && NOT for record is SCO))) &&
4291 // (phone state is NOT ringing && NOT in call)
4292 //
4293 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004294 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004295 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4296 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4297 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4298 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004299
4300 mpClientInterface->restoreOutput(a2dpOutput);
4301 mA2dpSuspended = false;
4302 }
4303 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004304 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004305 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4306 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4307 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4308 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004309
4310 mpClientInterface->suspendOutput(a2dpOutput);
4311 mA2dpSuspended = true;
4312 }
4313 }
4314}
4315
Eric Laurentc75307b2015-03-17 15:29:32 -07004316audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4317 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004318{
4319 audio_devices_t device = AUDIO_DEVICE_NONE;
4320
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004321 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004322 if (index >= 0) {
4323 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4324 if (patchDesc->mUid != mUidCached) {
4325 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004326 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 return outputDesc->device();
4328 }
4329 }
4330
Eric Laurente552edb2014-03-10 17:42:56 -07004331 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004332 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004333 // use device for strategy enforced audible
4334 // 2: we are in call or the strategy phone is active on the output:
4335 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004336 // 3: the strategy for enforced audible is active but not enforced on the output:
4337 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004338 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004339 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004340 // 5: the strategy accessibility is active on the output:
4341 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004342 // 6: the strategy "respectful" sonification is active on the output:
4343 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004344 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004345 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004346 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004347 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004348 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004349 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004350 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004351 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004352 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4353 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004354 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004355 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004356 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004357 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004358 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004360 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4361 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004362 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004363 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004364 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004365 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004366 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004367 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004368 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004369 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004370 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004371 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004372 }
4373
Eric Laurent1c333e22014-05-20 10:48:17 -07004374 ALOGV("getNewOutputDevice() selected device %x", device);
4375 return device;
4376}
4377
Eric Laurent232f26f2016-02-17 18:06:27 -08004378audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004379{
Eric Laurent232f26f2016-02-17 18:06:27 -08004380 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004381
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004382 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 if (index >= 0) {
4384 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4385 if (patchDesc->mUid != mUidCached) {
4386 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004387 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004388 return inputDesc->mDevice;
4389 }
4390 }
4391
Eric Laurent232f26f2016-02-17 18:06:27 -08004392 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004393
Eric Laurente552edb2014-03-10 17:42:56 -07004394 return device;
4395}
4396
Eric Laurent794fde22016-03-11 09:50:45 -08004397bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4398 audio_stream_type_t stream2) {
4399 return ((stream1 == stream2) ||
4400 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4401 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004402}
4403
Eric Laurente0720872014-03-11 09:30:41 -07004404uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004405 return (uint32_t)getStrategy(stream);
4406}
4407
Eric Laurente0720872014-03-11 09:30:41 -07004408audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004409 // By checking the range of stream before calling getStrategy, we avoid
4410 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4411 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004412 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 return AUDIO_DEVICE_NONE;
4414 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004415 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004416 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4417 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004418 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 }
Eric Laurent794fde22016-03-11 09:50:45 -08004420 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004421 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004422 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004423 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4424 for (size_t i = 0; i < outputs.size(); i++) {
4425 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004426 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004427 curDevices |= outputDesc->device();
4428 }
4429 }
4430 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004431 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004432
4433 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4434 and doesn't really need to.*/
4435 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4436 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4437 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4438 }
Eric Laurente552edb2014-03-10 17:42:56 -07004439 return devices;
4440}
4441
François Gaffie2110e042015-03-24 08:41:51 +01004442routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4443{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004444 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004445 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004446}
4447
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004448uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4449 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004450 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4451 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4452 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004453 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4454 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4455 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004456 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004457 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004458}
4459
Eric Laurente0720872014-03-11 09:30:41 -07004460void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004461 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004462 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004463 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4464 updateDevicesAndOutputs();
4465 break;
4466 default:
4467 break;
4468 }
4469}
4470
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004471uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004472
4473 // skip beacon mute management if a dedicated TTS output is available
4474 if (mTtsOutputAvailable) {
4475 return 0;
4476 }
4477
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004478 switch(event) {
4479 case STARTING_OUTPUT:
4480 mBeaconMuteRefCount++;
4481 break;
4482 case STOPPING_OUTPUT:
4483 if (mBeaconMuteRefCount > 0) {
4484 mBeaconMuteRefCount--;
4485 }
4486 break;
4487 case STARTING_BEACON:
4488 mBeaconPlayingRefCount++;
4489 break;
4490 case STOPPING_BEACON:
4491 if (mBeaconPlayingRefCount > 0) {
4492 mBeaconPlayingRefCount--;
4493 }
4494 break;
4495 }
4496
4497 if (mBeaconMuteRefCount > 0) {
4498 // any playback causes beacon to be muted
4499 return setBeaconMute(true);
4500 } else {
4501 // no other playback: unmute when beacon starts playing, mute when it stops
4502 return setBeaconMute(mBeaconPlayingRefCount == 0);
4503 }
4504}
4505
4506uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4507 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4508 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4509 // keep track of muted state to avoid repeating mute/unmute operations
4510 if (mBeaconMuted != mute) {
4511 // mute/unmute AUDIO_STREAM_TTS on all outputs
4512 ALOGV("\t muting %d", mute);
4513 uint32_t maxLatency = 0;
4514 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004515 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004516 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004517 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004518 0 /*delay*/, AUDIO_DEVICE_NONE);
4519 const uint32_t latency = desc->latency() * 2;
4520 if (latency > maxLatency) {
4521 maxLatency = latency;
4522 }
4523 }
4524 mBeaconMuted = mute;
4525 return maxLatency;
4526 }
4527 return 0;
4528}
4529
Eric Laurente0720872014-03-11 09:30:41 -07004530audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004531 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004532{
Paul McLeanaa981192015-03-21 09:55:15 -07004533 // Routing
4534 // see if we have an explicit route
4535 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4536 // (getStrategy(stream)).
4537 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4538 // and activity count is non-zero
4539 // the device = the device from the descriptor in the RouteMap, and exit.
4540 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4541 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004542 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4543 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004544 return route->mDeviceDescriptor->type();
4545 }
4546 }
4547
Eric Laurente552edb2014-03-10 17:42:56 -07004548 if (fromCache) {
4549 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4550 strategy, mDeviceForStrategy[strategy]);
4551 return mDeviceForStrategy[strategy];
4552 }
François Gaffie2110e042015-03-24 08:41:51 +01004553 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004554}
4555
Eric Laurente0720872014-03-11 09:30:41 -07004556void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004557{
4558 for (int i = 0; i < NUM_STRATEGIES; i++) {
4559 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4560 }
4561 mPreviousOutputs = mOutputs;
4562}
4563
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004564uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004565 audio_devices_t prevDevice,
4566 uint32_t delayMs)
4567{
4568 // mute/unmute strategies using an incompatible device combination
4569 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4570 // if unmuting, unmute only after the specified delay
4571 if (outputDesc->isDuplicated()) {
4572 return 0;
4573 }
4574
4575 uint32_t muteWaitMs = 0;
4576 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004577 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004578
4579 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4580 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004581 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004582 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4583 bool doMute = false;
4584
4585 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4586 doMute = true;
4587 outputDesc->mStrategyMutedByDevice[i] = true;
4588 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4589 doMute = true;
4590 outputDesc->mStrategyMutedByDevice[i] = false;
4591 }
Eric Laurent99401132014-05-07 19:48:15 -07004592 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004593 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004594 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 // skip output if it does not share any device with current output
4596 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4597 == AUDIO_DEVICE_NONE) {
4598 continue;
4599 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004600 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4601 mute ? "muting" : "unmuting", i, curDevice);
4602 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004603 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004604 if (mute) {
4605 // FIXME: should not need to double latency if volume could be applied
4606 // immediately by the audioflinger mixer. We must account for the delay
4607 // between now and the next time the audioflinger thread for this output
4608 // will process a buffer (which corresponds to one buffer size,
4609 // usually 1/2 or 1/4 of the latency).
4610 if (muteWaitMs < desc->latency() * 2) {
4611 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004612 }
4613 }
4614 }
4615 }
4616 }
4617 }
4618
Eric Laurent99401132014-05-07 19:48:15 -07004619 // temporary mute output if device selection changes to avoid volume bursts due to
4620 // different per device volumes
4621 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004622 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4623 // temporary mute duration is conservatively set to 4 times the reported latency
4624 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4625 if (muteWaitMs < tempMuteWaitMs) {
4626 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004627 }
Eric Laurentdc462862016-07-19 12:29:53 -07004628
Eric Laurent99401132014-05-07 19:48:15 -07004629 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004630 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004631 // make sure that we do not start the temporary mute period too early in case of
4632 // delayed device change
4633 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004634 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004635 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004636 }
4637 }
4638 }
4639
Eric Laurente552edb2014-03-10 17:42:56 -07004640 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4641 if (muteWaitMs > delayMs) {
4642 muteWaitMs -= delayMs;
4643 usleep(muteWaitMs * 1000);
4644 return muteWaitMs;
4645 }
4646 return 0;
4647}
4648
Eric Laurentc75307b2015-03-17 15:29:32 -07004649uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004650 audio_devices_t device,
4651 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004652 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004653 audio_patch_handle_t *patchHandle,
4654 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004655{
Eric Laurentc75307b2015-03-17 15:29:32 -07004656 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004657 AudioParameter param;
4658 uint32_t muteWaitMs;
4659
4660 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004661 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4662 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004663 return muteWaitMs;
4664 }
4665 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4666 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004667 if ((device != AUDIO_DEVICE_NONE) &&
4668 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004669 return 0;
4670 }
4671
4672 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004673 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004674
4675 audio_devices_t prevDevice = outputDesc->mDevice;
4676
Paul McLeanaa981192015-03-21 09:55:15 -07004677 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004678
4679 if (device != AUDIO_DEVICE_NONE) {
4680 outputDesc->mDevice = device;
4681 }
4682 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4683
4684 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004685 // the requested device is AUDIO_DEVICE_NONE
4686 // OR the requested device is the same as current device
4687 // AND force is not specified
4688 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004689 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004690 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4691 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004692 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004693 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004694 return muteWaitMs;
4695 }
4696
4697 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004698
Eric Laurente552edb2014-03-10 17:42:56 -07004699 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004700 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004701 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004702 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004703 DeviceVector deviceList;
4704 if ((address == NULL) || (strlen(address) == 0)) {
4705 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4706 } else {
4707 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4708 }
4709
Eric Laurent1c333e22014-05-20 10:48:17 -07004710 if (!deviceList.isEmpty()) {
4711 struct audio_patch patch;
4712 outputDesc->toAudioPortConfig(&patch.sources[0]);
4713 patch.num_sources = 1;
4714 patch.num_sinks = 0;
4715 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4716 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004717 patch.num_sinks++;
4718 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 ssize_t index;
4720 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4721 index = mAudioPatches.indexOfKey(*patchHandle);
4722 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004723 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 }
4725 sp< AudioPatch> patchDesc;
4726 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4727 if (index >= 0) {
4728 patchDesc = mAudioPatches.valueAt(index);
4729 afPatchHandle = patchDesc->mAfPatchHandle;
4730 }
4731
Eric Laurent1c333e22014-05-20 10:48:17 -07004732 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 &afPatchHandle,
4734 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004735 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4736 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004738 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004740 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 addAudioPatch(patchDesc->mHandle, patchDesc);
4742 } else {
4743 patchDesc->mPatch = patch;
4744 }
4745 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 if (patchHandle) {
4747 *patchHandle = patchDesc->mHandle;
4748 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004749 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004750 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004751 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004752 }
4753 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004754
4755 // inform all input as well
4756 for (size_t i = 0; i < mInputs.size(); i++) {
4757 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004758 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004759 AudioParameter inputCmd = AudioParameter();
4760 ALOGV("%s: inform input %d of device:%d", __func__,
4761 inputDescriptor->mIoHandle, device);
4762 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4763 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4764 inputCmd.toString(),
4765 delayMs);
4766 }
4767 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004768 }
Eric Laurente552edb2014-03-10 17:42:56 -07004769
4770 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004771 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004772
4773 return muteWaitMs;
4774}
4775
Eric Laurentc75307b2015-03-17 15:29:32 -07004776status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004777 int delayMs,
4778 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004779{
Eric Laurent6a94d692014-05-20 11:18:06 -07004780 ssize_t index;
4781 if (patchHandle) {
4782 index = mAudioPatches.indexOfKey(*patchHandle);
4783 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004784 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 }
4786 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004787 return INVALID_OPERATION;
4788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4790 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004791 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004792 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 removeAudioPatch(patchDesc->mHandle);
4794 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004795 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 return status;
4797}
4798
4799status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4800 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 bool force,
4802 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004803{
4804 status_t status = NO_ERROR;
4805
Eric Laurent1f2f2232014-06-02 12:01:23 -07004806 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004807 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4808 inputDesc->mDevice = device;
4809
4810 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4811 if (!deviceList.isEmpty()) {
4812 struct audio_patch patch;
4813 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004814 // AUDIO_SOURCE_HOTWORD is for internal use only:
4815 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004816 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004817 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004818 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4819 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004820 patch.num_sinks = 1;
4821 //only one input device for now
4822 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004823 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 ssize_t index;
4825 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4826 index = mAudioPatches.indexOfKey(*patchHandle);
4827 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004828 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 }
4830 sp< AudioPatch> patchDesc;
4831 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4832 if (index >= 0) {
4833 patchDesc = mAudioPatches.valueAt(index);
4834 afPatchHandle = patchDesc->mAfPatchHandle;
4835 }
4836
Eric Laurent1c333e22014-05-20 10:48:17 -07004837 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004839 0);
4840 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004843 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004844 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004845 addAudioPatch(patchDesc->mHandle, patchDesc);
4846 } else {
4847 patchDesc->mPatch = patch;
4848 }
4849 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 if (patchHandle) {
4851 *patchHandle = patchDesc->mHandle;
4852 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004853 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004855 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004856 }
4857 }
4858 }
4859 return status;
4860}
4861
Eric Laurent6a94d692014-05-20 11:18:06 -07004862status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4863 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004864{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004865 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 ssize_t index;
4867 if (patchHandle) {
4868 index = mAudioPatches.indexOfKey(*patchHandle);
4869 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004870 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 }
4872 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004873 return INVALID_OPERATION;
4874 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4876 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004877 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004878 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004879 removeAudioPatch(patchDesc->mHandle);
4880 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004881 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004882 return status;
4883}
4884
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004885sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07004886 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004887 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004888 audio_format_t& format,
4889 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004890 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004891{
4892 // Choose an input profile based on the requested capture parameters: select the first available
4893 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004894 //
4895 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4896 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004897
4898 for (size_t i = 0; i < mHwModules.size(); i++)
4899 {
4900 if (mHwModules[i]->mHandle == 0) {
4901 continue;
4902 }
4903 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4904 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004905 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004906 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004907 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004908 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004909 format,
4910 &format /*updatedFormat*/,
4911 channelMask,
4912 &channelMask /*updatedChannelMask*/,
4913 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004914
Eric Laurente552edb2014-03-10 17:42:56 -07004915 return profile;
4916 }
4917 }
4918 }
4919 return NULL;
4920}
4921
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004922
4923audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004924 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004925{
François Gaffie036e1e92015-03-19 10:16:24 +01004926 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4927 audio_devices_t selectedDeviceFromMix =
4928 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004929
François Gaffie036e1e92015-03-19 10:16:24 +01004930 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4931 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004932 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004933 return getDeviceForInputSource(inputSource);
4934}
4935
4936audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4937{
Paul McLean466dc8e2015-04-17 13:15:36 -06004938 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4939 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004940 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004941 return route->mDeviceDescriptor->type();
4942 }
4943 }
4944
4945 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004946}
4947
Eric Laurente0720872014-03-11 09:30:41 -07004948float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004949 int index,
4950 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004951{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07004952 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004953 // if a headset is connected, apply the following rules to ring tones and notifications
4954 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07004955 // - always attenuate notifications volume by 6dB
4956 // - attenuate ring tones volume by 6dB unless music is not playing and
4957 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07004958 // - if music is playing, always limit the volume to current music volume,
4959 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004960 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004961 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4962 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4963 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4964 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4965 ((stream_strategy == STRATEGY_SONIFICATION)
4966 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004967 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004968 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004969 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004970 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004971 // when the phone is ringing we must consider that music could have been paused just before
4972 // by the music application and behave as if music was active if the last music track was
4973 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004974 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004975 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07004976 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004977 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004978 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004979 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4980 musicDevice),
4981 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004982 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4983 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07004984 if (volumeDB > minVolDB) {
4985 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07004986 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004987 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07004988 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4989 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
4990 // on A2DP, also ensure notification volume is not too low compared to media when
4991 // intended to be played
4992 if ((volumeDB > -96.0f) &&
4993 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
4994 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
4995 stream, device,
4996 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
4997 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
4998 }
4999 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005000 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5001 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005002 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005003 }
5004 }
5005
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005006 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005007}
5008
Eric Laurente0720872014-03-11 09:30:41 -07005009status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005010 int index,
5011 const sp<AudioOutputDescriptor>& outputDesc,
5012 audio_devices_t device,
5013 int delayMs,
5014 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005015{
Eric Laurente552edb2014-03-10 17:42:56 -07005016 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005017 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005018 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005019 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005020 return NO_ERROR;
5021 }
François Gaffie2110e042015-03-24 08:41:51 +01005022 audio_policy_forced_cfg_t forceUseForComm =
5023 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005024 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005025 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5026 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005027 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005028 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005029 return INVALID_OPERATION;
5030 }
5031
Eric Laurentc75307b2015-03-17 15:29:32 -07005032 if (device == AUDIO_DEVICE_NONE) {
5033 device = outputDesc->device();
5034 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005035
Eric Laurentffbc80f2015-03-18 18:30:19 -07005036 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005037 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005038 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005039 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005040
Eric Laurentffbc80f2015-03-18 18:30:19 -07005041 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005042
Eric Laurent3b73df72014-03-11 09:06:29 -07005043 if (stream == AUDIO_STREAM_VOICE_CALL ||
5044 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005045 float voiceVolume;
5046 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005047 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005048 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005049 } else {
5050 voiceVolume = 1.0;
5051 }
5052
Eric Laurent18fba842016-03-31 14:41:26 -07005053 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005054 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5055 mLastVoiceVolume = voiceVolume;
5056 }
5057 }
5058
5059 return NO_ERROR;
5060}
5061
Eric Laurentc75307b2015-03-17 15:29:32 -07005062void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5063 audio_devices_t device,
5064 int delayMs,
5065 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005066{
Eric Laurentc75307b2015-03-17 15:29:32 -07005067 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005068
Eric Laurent794fde22016-03-11 09:50:45 -08005069 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005070 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005071 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005072 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005073 device,
5074 delayMs,
5075 force);
5076 }
5077}
5078
Eric Laurente0720872014-03-11 09:30:41 -07005079void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005080 bool on,
5081 const sp<AudioOutputDescriptor>& outputDesc,
5082 int delayMs,
5083 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005084{
Eric Laurent72249d52015-06-08 11:12:15 -07005085 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5086 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005087 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005088 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005089 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005090 }
5091 }
5092}
5093
Eric Laurente0720872014-03-11 09:30:41 -07005094void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005095 bool on,
5096 const sp<AudioOutputDescriptor>& outputDesc,
5097 int delayMs,
5098 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005099{
Eric Laurente552edb2014-03-10 17:42:56 -07005100 if (device == AUDIO_DEVICE_NONE) {
5101 device = outputDesc->device();
5102 }
5103
Eric Laurentc75307b2015-03-17 15:29:32 -07005104 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5105 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005106
5107 if (on) {
5108 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005109 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005110 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005111 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005113 }
5114 }
5115 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5116 outputDesc->mMuteCount[stream]++;
5117 } else {
5118 if (outputDesc->mMuteCount[stream] == 0) {
5119 ALOGV("setStreamMute() unmuting non muted stream!");
5120 return;
5121 }
5122 if (--outputDesc->mMuteCount[stream] == 0) {
5123 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005124 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005125 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005126 device,
5127 delayMs);
5128 }
5129 }
5130}
5131
Eric Laurente0720872014-03-11 09:30:41 -07005132void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005133 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005134{
Eric Laurent87ffa392015-05-22 10:32:38 -07005135 if(!hasPrimaryOutput()) {
5136 return;
5137 }
5138
Eric Laurente552edb2014-03-10 17:42:56 -07005139 // if the stream pertains to sonification strategy and we are in call we must
5140 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5141 // in the device used for phone strategy and play the tone if the selected device does not
5142 // interfere with the device used for phone strategy
5143 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5144 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005145 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005146 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5147 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005148 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005149 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5150 stream, starting, outputDesc->mDevice, stateChange);
5151 if (outputDesc->mRefCount[stream]) {
5152 int muteCount = 1;
5153 if (stateChange) {
5154 muteCount = outputDesc->mRefCount[stream];
5155 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005156 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005157 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5158 for (int i = 0; i < muteCount; i++) {
5159 setStreamMute(stream, starting, mPrimaryOutput);
5160 }
5161 } else {
5162 ALOGV("handleIncallSonification() high visibility");
5163 if (outputDesc->device() &
5164 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5165 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5166 for (int i = 0; i < muteCount; i++) {
5167 setStreamMute(stream, starting, mPrimaryOutput);
5168 }
5169 }
5170 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005171 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5172 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005173 } else {
5174 mpClientInterface->stopTone();
5175 }
5176 }
5177 }
5178 }
5179}
5180
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005181audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5182{
5183 // flags to stream type mapping
5184 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5185 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5186 }
5187 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5188 return AUDIO_STREAM_BLUETOOTH_SCO;
5189 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005190 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5191 return AUDIO_STREAM_TTS;
5192 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005193
5194 // usage to stream type mapping
5195 switch (attr->usage) {
5196 case AUDIO_USAGE_MEDIA:
5197 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005198 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5199 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005200 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5201 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005202 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5203 return AUDIO_STREAM_SYSTEM;
5204 case AUDIO_USAGE_VOICE_COMMUNICATION:
5205 return AUDIO_STREAM_VOICE_CALL;
5206
5207 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5208 return AUDIO_STREAM_DTMF;
5209
5210 case AUDIO_USAGE_ALARM:
5211 return AUDIO_STREAM_ALARM;
5212 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5213 return AUDIO_STREAM_RING;
5214
5215 case AUDIO_USAGE_NOTIFICATION:
5216 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5217 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5218 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5219 case AUDIO_USAGE_NOTIFICATION_EVENT:
5220 return AUDIO_STREAM_NOTIFICATION;
5221
5222 case AUDIO_USAGE_UNKNOWN:
5223 default:
5224 return AUDIO_STREAM_MUSIC;
5225 }
5226}
Eric Laurente83b55d2014-11-14 10:06:21 -08005227
François Gaffie53615e22015-03-19 09:24:12 +01005228bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5229{
Eric Laurente83b55d2014-11-14 10:06:21 -08005230 // has flags that map to a strategy?
5231 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5232 return true;
5233 }
5234
5235 // has known usage?
5236 switch (paa->usage) {
5237 case AUDIO_USAGE_UNKNOWN:
5238 case AUDIO_USAGE_MEDIA:
5239 case AUDIO_USAGE_VOICE_COMMUNICATION:
5240 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5241 case AUDIO_USAGE_ALARM:
5242 case AUDIO_USAGE_NOTIFICATION:
5243 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5244 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5245 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5246 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5247 case AUDIO_USAGE_NOTIFICATION_EVENT:
5248 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5249 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5250 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5251 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005252 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005253 break;
5254 default:
5255 return false;
5256 }
5257 return true;
5258}
5259
Chih-Hung Hsieh36d0ca12016-08-09 14:31:32 -07005260bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005261 routing_strategy strategy, uint32_t inPastMs,
5262 nsecs_t sysTime) const
5263{
5264 if ((sysTime == 0) && (inPastMs != 0)) {
5265 sysTime = systemTime();
5266 }
Eric Laurent794fde22016-03-11 09:50:45 -08005267 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005268 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5269 (NUM_STRATEGIES == strategy)) &&
5270 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5271 return true;
5272 }
5273 }
5274 return false;
5275}
5276
François Gaffie2110e042015-03-24 08:41:51 +01005277audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5278{
5279 return mEngine->getForceUse(usage);
5280}
5281
5282bool AudioPolicyManager::isInCall()
5283{
5284 return isStateInCall(mEngine->getPhoneState());
5285}
5286
5287bool AudioPolicyManager::isStateInCall(int state)
5288{
5289 return is_state_in_call(state);
5290}
5291
Eric Laurentd60560a2015-04-10 11:31:20 -07005292void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5293{
5294 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5295 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5296 if (sourceDesc->mDevice->equals(deviceDesc)) {
5297 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5298 stopAudioSource(sourceDesc->getHandle());
5299 }
5300 }
5301
5302 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5303 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5304 bool release = false;
5305 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5306 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5307 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5308 source->ext.device.type == deviceDesc->type()) {
5309 release = true;
5310 }
5311 }
5312 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5313 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5314 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5315 sink->ext.device.type == deviceDesc->type()) {
5316 release = true;
5317 }
5318 }
5319 if (release) {
5320 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5321 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5322 }
5323 }
5324}
5325
Phil Burk09bc4612016-02-24 15:58:15 -08005326// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005327void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5328 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005329 // TODO Set this based on Config properties.
5330 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005331
5332 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5333 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005334 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005335
5336 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005337 bool supportsAC3 = false;
5338 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005339 bool supportsIEC61937 = false;
5340 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5341 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005342 switch (format) {
5343 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005344 supportsAC3 = true;
5345 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005346 case AUDIO_FORMAT_E_AC3:
5347 case AUDIO_FORMAT_DTS:
5348 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005349 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005350 break;
5351 case AUDIO_FORMAT_IEC61937:
5352 supportsIEC61937 = true;
5353 break;
5354 default:
5355 break;
5356 }
5357 }
Phil Burk09bc4612016-02-24 15:58:15 -08005358
5359 // Modify formats based on surround preferences.
5360 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005361 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5362 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5363 // Remove surround sound related formats.
5364 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5365 audio_format_t format = formats[formatIndex];
5366 switch(format) {
5367 case AUDIO_FORMAT_AC3:
5368 case AUDIO_FORMAT_E_AC3:
5369 case AUDIO_FORMAT_DTS:
5370 case AUDIO_FORMAT_DTS_HD:
5371 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005372 formats.removeAt(formatIndex);
5373 break;
5374 default:
5375 formatIndex++; // keep it
5376 break;
5377 }
Phil Burk09bc4612016-02-24 15:58:15 -08005378 }
Phil Burk07ac1142016-03-25 13:39:29 -07005379 supportsAC3 = false;
5380 supportsOtherSurround = false;
5381 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005382 }
Phil Burk07ac1142016-03-25 13:39:29 -07005383 } else { // AUTO or ALWAYS
5384 // Most TVs support AC3 even if they do not report it in the EDID.
5385 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5386 && !supportsAC3) {
5387 formats.add(AUDIO_FORMAT_AC3);
5388 supportsAC3 = true;
5389 }
5390
5391 // If ALWAYS, add support for raw surround formats if all are missing.
5392 // This assumes that if any of these formats are reported by the HAL
5393 // then the report is valid and should not be modified.
5394 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5395 && !supportsOtherSurround) {
5396 formats.add(AUDIO_FORMAT_E_AC3);
5397 formats.add(AUDIO_FORMAT_DTS);
5398 formats.add(AUDIO_FORMAT_DTS_HD);
5399 supportsOtherSurround = true;
5400 }
5401
5402 // Add support for IEC61937 if any raw surround supported.
5403 // The HAL could do this but add it here, just in case.
5404 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5405 formats.add(AUDIO_FORMAT_IEC61937);
5406 supportsIEC61937 = true;
5407 }
Phil Burk09bc4612016-02-24 15:58:15 -08005408 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005409}
5410
5411// Modify the list of channel masks supported.
5412void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5413 ChannelsVector &channelMasks = *channelMasksPtr;
5414 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5415 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5416
5417 // If NEVER, then remove support for channelMasks > stereo.
5418 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5419 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5420 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5421 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5422 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5423 channelMasks.removeAt(maskIndex);
5424 } else {
5425 maskIndex++;
5426 }
5427 }
5428 // If ALWAYS, then make sure we at least support 5.1
5429 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5430 bool supports5dot1 = false;
5431 // Are there any channel masks that can be considered "surround"?
5432 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5433 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5434 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5435 supports5dot1 = true;
5436 break;
5437 }
5438 }
5439 // If not then add 5.1 support.
5440 if (!supports5dot1) {
5441 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5442 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5443 }
Phil Burk09bc4612016-02-24 15:58:15 -08005444 }
5445}
5446
Phil Burk00eeb322016-03-31 12:41:00 -07005447void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5448 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005449 AudioProfileVector &profiles)
5450{
5451 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005452
François Gaffie112b0af2015-11-19 16:13:25 +01005453 // Format MUST be checked first to update the list of AudioProfile
5454 if (profiles.hasDynamicFormat()) {
5455 reply = mpClientInterface->getParameters(ioHandle,
5456 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005457 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005458 AudioParameter repliedParameters(reply);
5459 if (repliedParameters.get(
5460 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005461 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5462 return;
5463 }
Phil Burk09bc4612016-02-24 15:58:15 -08005464 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005465 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005466 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005467 }
Phil Burk09bc4612016-02-24 15:58:15 -08005468 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005469 }
5470 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5471
Eric Laurent20eb3a42016-01-26 18:39:17 -08005472 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005473 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005474 ChannelsVector channelMasks;
5475 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005476 AudioParameter requestedParameters;
5477 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5478
5479 if (profiles.hasDynamicRateFor(format)) {
5480 reply = mpClientInterface->getParameters(ioHandle,
5481 requestedParameters.toString() + ";" +
5482 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5483 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005484 AudioParameter repliedParameters(reply);
5485 if (repliedParameters.get(
5486 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5487 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005488 }
5489 }
5490 if (profiles.hasDynamicChannelsFor(format)) {
5491 reply = mpClientInterface->getParameters(ioHandle,
5492 requestedParameters.toString() + ";" +
5493 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5494 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005495 AudioParameter repliedParameters(reply);
5496 if (repliedParameters.get(
5497 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5498 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005499 if (device == AUDIO_DEVICE_OUT_HDMI) {
5500 filterSurroundChannelMasks(&channelMasks);
5501 }
François Gaffie112b0af2015-11-19 16:13:25 +01005502 }
5503 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005504 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005505 }
5506}
Eric Laurentd60560a2015-04-10 11:31:20 -07005507
Eric Laurente552edb2014-03-10 17:42:56 -07005508}; // namespace android