blob: a714041ac60227155c6cbd37b1df9aa5deabc9e5 [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>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070039#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070040#include <audio_policy_conf.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 ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070073 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020074 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 Laurentfb66dd92016-01-28 18:32:03 -0800451 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
452 for (size_t i = 0; i < activeInputs.size(); i++) {
453 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
454 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
455 AudioSessionCollection activeSessions =
456 activeDesc->getAudioSessions(true /*activeOnly*/);
457 for (size_t j = 0; j < activeSessions.size(); j++) {
458 audio_session_t activeSession = activeSessions.keyAt(j);
459 stopInput(activeDesc->mIoHandle, activeSession);
460 releaseInput(activeDesc->mIoHandle, activeSession);
461 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700462 }
463 }
464
Eric Laurentc2730ba2014-07-20 15:47:07 -0700465 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700466 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
468 status);
469 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100470 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471 mCallTxPatch->mAfPatchHandle = afPatchHandle;
472 mCallTxPatch->mUid = mUidCached;
473 }
474 }
Eric Laurentdc462862016-07-19 12:29:53 -0700475
476 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477}
478
Eric Laurente0720872014-03-11 09:30:41 -0700479void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700480{
481 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100482 // store previous phone state for management of sonification strategy below
483 int oldState = mEngine->getPhoneState();
484
485 if (mEngine->setPhoneState(state) != NO_ERROR) {
486 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return;
488 }
François Gaffie2110e042015-03-24 08:41:51 +0100489 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700490 // if leaving call state, handle special case of active streams
491 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700492 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700493 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800494 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700495 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700496 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800497
Eric Laurent63dea1d2015-07-02 17:10:28 -0700498 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800499 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700500 }
501
François Gaffie2110e042015-03-24 08:41:51 +0100502 /**
503 * Switching to or from incall state or switching between telephony and VoIP lead to force
504 * routing command.
505 */
506 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
507 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700508
509 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700510 checkA2dpSuspend();
511 checkOutputForAllStrategies();
512 updateDevicesAndOutputs();
513
Eric Laurente552edb2014-03-10 17:42:56 -0700514 int delayMs = 0;
515 if (isStateInCall(state)) {
516 nsecs_t sysTime = systemTime();
517 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700518 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700519 // mute media and sonification strategies and delay device switch by the largest
520 // latency of any output where either strategy is active.
521 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100522 if ((isStrategyActive(desc, STRATEGY_MEDIA,
523 SONIFICATION_HEADSET_MUSIC_DELAY,
524 sysTime) ||
525 isStrategyActive(desc, STRATEGY_SONIFICATION,
526 SONIFICATION_HEADSET_MUSIC_DELAY,
527 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700528 (delayMs < (int)desc->latency()*2)) {
529 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700530 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700531 setStrategyMute(STRATEGY_MEDIA, true, desc);
532 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700533 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700534 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
535 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700536 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
537 }
538 }
539
Eric Laurent87ffa392015-05-22 10:32:38 -0700540 if (hasPrimaryOutput()) {
541 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
542 // the device returned is not necessarily reachable via this output
543 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
544 // force routing command to audio hardware when ending call
545 // even if no device change is needed
546 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
547 rxDevice = mPrimaryOutput->device();
548 }
Eric Laurente552edb2014-03-10 17:42:56 -0700549
Eric Laurent87ffa392015-05-22 10:32:38 -0700550 if (state == AUDIO_MODE_IN_CALL) {
551 updateCallRouting(rxDevice, delayMs);
552 } else if (oldState == AUDIO_MODE_IN_CALL) {
553 if (mCallRxPatch != 0) {
554 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
555 mCallRxPatch.clear();
556 }
557 if (mCallTxPatch != 0) {
558 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
559 mCallTxPatch.clear();
560 }
561 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
562 } else {
563 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700564 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700565 }
Eric Laurente552edb2014-03-10 17:42:56 -0700566 // if entering in call state, handle special case of active streams
567 // pertaining to sonification strategy see handleIncallSonification()
568 if (isStateInCall(state)) {
569 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800570 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700571 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700572 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700573
574 // force reevaluating accessibility routing when call starts
575 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700576 }
577
578 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700579 if (state == AUDIO_MODE_RINGTONE &&
580 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700581 mLimitRingtoneVolume = true;
582 } else {
583 mLimitRingtoneVolume = false;
584 }
585}
586
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700587audio_mode_t AudioPolicyManager::getPhoneState() {
588 return mEngine->getPhoneState();
589}
590
Eric Laurente0720872014-03-11 09:30:41 -0700591void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700592 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700593{
François Gaffie2110e042015-03-24 08:41:51 +0100594 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700595
François Gaffie2110e042015-03-24 08:41:51 +0100596 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
597 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
598 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
François Gaffie2110e042015-03-24 08:41:51 +0100600 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
601 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
602 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700603
604 // check for device and output changes triggered by new force usage
605 checkA2dpSuspend();
606 checkOutputForAllStrategies();
607 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800608
Eric Laurentdc462862016-07-19 12:29:53 -0700609 //FIXME: workaround for truncated touch sounds
610 // to be removed when the problem is handled by system UI
611 uint32_t delayMs = 0;
612 uint32_t waitMs = 0;
613 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
614 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
615 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700616 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700618 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurente552edb2014-03-10 17:42:56 -0700620 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700621 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
622 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
623 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700624 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
625 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurente552edb2014-03-10 17:42:56 -0700627 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700628 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700629 }
630 }
631
Eric Laurentfb66dd92016-01-28 18:32:03 -0800632 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
633 for (size_t i = 0; i < activeInputs.size(); i++) {
634 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
635 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700636 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800637 if (activeDesc->mProfile->getSupportedDevices().types() &
638 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
639 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700640 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800641 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
Eric Laurente552edb2014-03-10 17:42:56 -0700644}
645
Eric Laurente0720872014-03-11 09:30:41 -0700646void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700647{
648 ALOGV("setSystemProperty() property %s, value %s", property, value);
649}
650
651// Find a direct output profile compatible with the parameters passed, even if the input flags do
652// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800653sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700654 audio_devices_t device,
655 uint32_t samplingRate,
656 audio_format_t format,
657 audio_channel_mask_t channelMask,
658 audio_output_flags_t flags)
659{
Eric Laurent861a6282015-05-18 15:40:16 -0700660 // only retain flags that will drive the direct output profile selection
661 // if explicitly requested
662 static const uint32_t kRelevantFlags =
663 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
664 flags =
665 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
666
667 sp<IOProfile> profile;
668
Eric Laurente552edb2014-03-10 17:42:56 -0700669 for (size_t i = 0; i < mHwModules.size(); i++) {
670 if (mHwModules[i]->mHandle == 0) {
671 continue;
672 }
673 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700674 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
675 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700676 samplingRate, NULL /*updatedSamplingRate*/,
677 format, NULL /*updatedFormat*/,
678 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700679 flags)) {
680 continue;
681 }
682 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100683 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700684 continue;
685 }
686 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100687 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700688 continue;
689 }
690 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100691 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700692 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700693 }
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
695 }
Eric Laurent861a6282015-05-18 15:40:16 -0700696 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700697}
698
Eric Laurente0720872014-03-11 09:30:41 -0700699audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags,
704 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700705{
Eric Laurent3b73df72014-03-11 09:06:29 -0700706 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
708 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
709 device, stream, samplingRate, format, channelMask, flags);
710
Eric Laurente83b55d2014-11-14 10:06:21 -0800711 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
712 stream, samplingRate,format, channelMask,
713 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700714}
715
Eric Laurente83b55d2014-11-14 10:06:21 -0800716status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
717 audio_io_handle_t *output,
718 audio_session_t session,
719 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700720 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800721 uint32_t samplingRate,
722 audio_format_t format,
723 audio_channel_mask_t channelMask,
724 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700725 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800726 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700727{
Eric Laurente83b55d2014-11-14 10:06:21 -0800728 audio_attributes_t attributes;
729 if (attr != NULL) {
730 if (!isValidAttributes(attr)) {
731 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
732 attr->usage, attr->content_type, attr->flags,
733 attr->tags);
734 return BAD_VALUE;
735 }
736 attributes = *attr;
737 } else {
738 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
739 ALOGE("getOutputForAttr(): invalid stream type");
740 return BAD_VALUE;
741 }
742 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700743 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700744 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800745 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100746 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800747 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100748 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800749 }
François Gaffie036e1e92015-03-19 10:16:24 +0100750 *stream = streamTypefromAttributesInt(&attributes);
751 *output = desc->mIoHandle;
752 ALOGV("getOutputForAttr() returns output %d", *output);
753 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800754 }
755 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
756 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
757 return BAD_VALUE;
758 }
759
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700760 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
761 " session %d selectedDeviceId %d",
762 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
763 session, selectedDeviceId);
764
765 *stream = streamTypefromAttributesInt(&attributes);
766
767 // Explicit routing?
768 sp<DeviceDescriptor> deviceDesc;
769 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
770 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
771 deviceDesc = mAvailableOutputDevices[i];
772 break;
773 }
774 }
775 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700776
Eric Laurente83b55d2014-11-14 10:06:21 -0800777 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700778 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700779
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700781 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
782 }
783
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700784 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700785 device, samplingRate, format, channelMask, flags);
786
Eric Laurente83b55d2014-11-14 10:06:21 -0800787 *output = getOutputForDevice(device, session, *stream,
788 samplingRate, format, channelMask,
789 flags, offloadInfo);
790 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700791 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800792 return INVALID_OPERATION;
793 }
Paul McLeanaa981192015-03-21 09:55:15 -0700794
Eric Laurente83b55d2014-11-14 10:06:21 -0800795 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796}
797
798audio_io_handle_t AudioPolicyManager::getOutputForDevice(
799 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800800 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700801 audio_stream_type_t stream,
802 uint32_t samplingRate,
803 audio_format_t format,
804 audio_channel_mask_t channelMask,
805 audio_output_flags_t flags,
806 const audio_offload_info_t *offloadInfo)
807{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700809 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700810
Eric Laurente552edb2014-03-10 17:42:56 -0700811#ifdef AUDIO_POLICY_TEST
812 if (mCurOutput != 0) {
813 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
814 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
815
816 if (mTestOutputs[mCurOutput] == 0) {
817 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700818 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
819 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700820 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700821 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700822 outputDesc->mFlags =
823 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700825 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
826 config.sample_rate = mTestSamplingRate;
827 config.channel_mask = mTestChannels;
828 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700829 if (offloadInfo != NULL) {
830 config.offload_info = *offloadInfo;
831 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700832 status = mpClientInterface->openOutput(0,
833 &mTestOutputs[mCurOutput],
834 &config,
835 &outputDesc->mDevice,
836 String8(""),
837 &outputDesc->mLatency,
838 outputDesc->mFlags);
839 if (status == NO_ERROR) {
840 outputDesc->mSamplingRate = config.sample_rate;
841 outputDesc->mFormat = config.format;
842 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700843 AudioParameter outputCmd = AudioParameter();
844 outputCmd.addInt(String8("set_id"),mCurOutput);
845 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
846 addOutput(mTestOutputs[mCurOutput], outputDesc);
847 }
848 }
849 return mTestOutputs[mCurOutput];
850 }
851#endif //AUDIO_POLICY_TEST
852
853 // open a direct output if required by specified parameters
854 //force direct flag if offload flag is set: offloading implies a direct output stream
855 // and all common behaviors are driven by checking only the direct flag
856 // this should normally be set appropriately in the policy configuration file
857 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700858 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700860 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
861 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
862 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800863 // only allow deep buffering for music stream type
864 if (stream != AUDIO_STREAM_MUSIC) {
865 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700866 } else if (/* stream == AUDIO_STREAM_MUSIC && */
867 flags == AUDIO_OUTPUT_FLAG_NONE &&
868 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
869 // use DEEP_BUFFER as default output for music stream type
870 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800871 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700872 if (stream == AUDIO_STREAM_TTS) {
873 flags = AUDIO_OUTPUT_FLAG_TTS;
874 }
Eric Laurente552edb2014-03-10 17:42:56 -0700875
Eric Laurentb732cf52014-09-24 19:08:21 -0700876 sp<IOProfile> profile;
877
878 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700879 // and not explicitly requested
880 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800881 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700882 audio_channel_count_from_out_mask(channelMask) <= 2) {
883 goto non_direct_output;
884 }
885
Andy Hung2ddee192015-12-18 17:34:44 -0800886 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
887 // This prevents creating an offloaded track and tearing it down immediately after start
888 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700889 // FIXME: We should check the audio session here but we do not have it in this context.
890 // This may prevent offloading in rare situations where effects are left active by apps
891 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700892
Eric Laurente552edb2014-03-10 17:42:56 -0700893 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800894 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700895 profile = getProfileForDirectOutput(device,
896 samplingRate,
897 format,
898 channelMask,
899 (audio_output_flags_t)flags);
900 }
901
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700904
905 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700907 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
908 outputDesc = desc;
909 // reuse direct output if currently open and configured with same parameters
910 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800911 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700912 (channelMask == outputDesc->mChannelMask)) {
913 outputDesc->mDirectOpenCount++;
914 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
915 return mOutputs.keyAt(i);
916 }
917 }
918 }
919 // close direct output if currently open and configured with different parameters
920 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700921 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700922 }
Eric Laurent861a6282015-05-18 15:40:16 -0700923
924 // if the selected profile is offloaded and no offload info was specified,
925 // create a default one
926 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100927 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700928 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
929 defaultOffloadInfo.sample_rate = samplingRate;
930 defaultOffloadInfo.channel_mask = channelMask;
931 defaultOffloadInfo.format = format;
932 defaultOffloadInfo.stream_type = stream;
933 defaultOffloadInfo.bit_rate = 0;
934 defaultOffloadInfo.duration_us = -1;
935 defaultOffloadInfo.has_video = true; // conservative
936 defaultOffloadInfo.is_streaming = true; // likely
937 offloadInfo = &defaultOffloadInfo;
938 }
939
Eric Laurentc75307b2015-03-17 15:29:32 -0700940 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700942 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700943 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700944 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
945 config.sample_rate = samplingRate;
946 config.channel_mask = channelMask;
947 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700948 if (offloadInfo != NULL) {
949 config.offload_info = *offloadInfo;
950 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700951 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700952 &output,
953 &config,
954 &outputDesc->mDevice,
955 String8(""),
956 &outputDesc->mLatency,
957 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700958
959 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700960 if (status != NO_ERROR ||
961 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800962 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700963 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700964 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
965 "format %d %d, channelMask %04x %04x", output, samplingRate,
966 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
967 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700968 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700969 mpClientInterface->closeOutput(output);
970 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800971 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800972 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800973 goto non_direct_output;
974 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700975 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700976 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700977 outputDesc->mSamplingRate = config.sample_rate;
978 outputDesc->mChannelMask = config.channel_mask;
979 outputDesc->mFormat = config.format;
980 outputDesc->mRefCount[stream] = 0;
981 outputDesc->mStopTime[stream] = 0;
982 outputDesc->mDirectOpenCount = 1;
983
Eric Laurente552edb2014-03-10 17:42:56 -0700984 audio_io_handle_t srcOutput = getOutputForEffect();
985 addOutput(output, outputDesc);
986 audio_io_handle_t dstOutput = getOutputForEffect();
987 if (dstOutput == output) {
988 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
989 }
990 mPreviousOutputs = mOutputs;
991 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700992 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700993 return output;
994 }
995
Eric Laurentb732cf52014-09-24 19:08:21 -0700996non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700997
998 // A request for HW A/V sync cannot fallback to a mixed output because time
999 // stamps are embedded in audio data
1000 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1001 return AUDIO_IO_HANDLE_NONE;
1002 }
1003
Eric Laurente552edb2014-03-10 17:42:56 -07001004 // ignoring channel mask due to downmix capability in mixer
1005
1006 // open a non direct output
1007
1008 // for non direct outputs, only PCM is supported
1009 if (audio_is_linear_pcm(format)) {
1010 // get which output is suitable for the specified stream. The actual
1011 // routing change will happen when startOutput() will be called
1012 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1013
Eric Laurent8838a382014-09-08 16:44:28 -07001014 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1015 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1016 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001017 }
1018 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1019 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1020
Paul McLeanaa981192015-03-21 09:55:15 -07001021 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001022
1023 return output;
1024}
1025
Eric Laurente0720872014-03-11 09:30:41 -07001026audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001027 audio_output_flags_t flags,
1028 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001029{
1030 // select one output among several that provide a path to a particular device or set of
1031 // devices (the list was previously build by getOutputsForDevice()).
1032 // The priority is as follows:
1033 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001034 // 2: the output with the bit depth the closest to the requested one
1035 // 3: the primary output
1036 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001037
1038 if (outputs.size() == 0) {
1039 return 0;
1040 }
1041 if (outputs.size() == 1) {
1042 return outputs[0];
1043 }
1044
1045 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001046 audio_io_handle_t outputForFlags = 0;
1047 audio_io_handle_t outputForPrimary = 0;
1048 audio_io_handle_t outputForFormat = 0;
1049 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1050 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001051
1052 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001053 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001055 // if a valid format is specified, skip output if not compatible
1056 if (format != AUDIO_FORMAT_INVALID) {
1057 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001058 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001059 continue;
1060 }
1061 } else if (!audio_is_linear_pcm(format)) {
1062 continue;
1063 }
Eric Laurente6930022016-02-11 10:20:40 -08001064 if (AudioPort::isBetterFormatMatch(
1065 outputDesc->mFormat, bestFormat, format)) {
1066 outputForFormat = outputs[i];
1067 bestFormat = outputDesc->mFormat;
1068 }
Eric Laurent8838a382014-09-08 16:44:28 -07001069 }
1070
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001071 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001072 if (commonFlags >= maxCommonFlags) {
1073 if (commonFlags == maxCommonFlags) {
1074 if (AudioPort::isBetterFormatMatch(
1075 outputDesc->mFormat, bestFormatForFlags, format)) {
1076 outputForFlags = outputs[i];
1077 bestFormatForFlags = outputDesc->mFormat;
1078 }
1079 } else {
1080 outputForFlags = outputs[i];
1081 maxCommonFlags = commonFlags;
1082 bestFormatForFlags = outputDesc->mFormat;
1083 }
Eric Laurente552edb2014-03-10 17:42:56 -07001084 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1085 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001086 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001087 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001088 }
1089 }
1090 }
1091
Eric Laurente6930022016-02-11 10:20:40 -08001092 if (outputForFlags != 0) {
1093 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001094 }
Eric Laurente6930022016-02-11 10:20:40 -08001095 if (outputForFormat != 0) {
1096 return outputForFormat;
1097 }
1098 if (outputForPrimary != 0) {
1099 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001100 }
1101
1102 return outputs[0];
1103}
1104
Eric Laurente0720872014-03-11 09:30:41 -07001105status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001106 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001107 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001108{
Paul McLeanaa981192015-03-21 09:55:15 -07001109 ALOGV("startOutput() output %d, stream %d, session %d",
1110 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001111 ssize_t index = mOutputs.indexOfKey(output);
1112 if (index < 0) {
1113 ALOGW("startOutput() unknown output %d", output);
1114 return BAD_VALUE;
1115 }
1116
Eric Laurentc75307b2015-03-17 15:29:32 -07001117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1118
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001119 // Routing?
1120 mOutputRoutes.incRouteActivity(session);
1121
Eric Laurentc75307b2015-03-17 15:29:32 -07001122 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001123 AudioMix *policyMix = NULL;
1124 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001125 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001126 policyMix = outputDesc->mPolicyMix;
1127 address = policyMix->mDeviceAddress.string();
1128 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1129 newDevice = policyMix->mDeviceType;
1130 } else {
1131 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1132 }
Eric Laurent493404d2015-04-21 15:07:36 -07001133 } else if (mOutputRoutes.hasRouteChanged(session)) {
1134 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001135 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001136 } else {
1137 newDevice = AUDIO_DEVICE_NONE;
1138 }
1139
1140 uint32_t delayMs = 0;
1141
Eric Laurentc40d9692016-04-13 19:14:13 -07001142 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001143
1144 if (status != NO_ERROR) {
1145 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001146 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001147 }
1148 // Automatically enable the remote submix input when output is started on a re routing mix
1149 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001150 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1151 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001152 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1153 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001154 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001155 "remote-submix");
1156 }
1157
1158 if (delayMs != 0) {
1159 usleep(delayMs * 1000);
1160 }
1161
1162 return status;
1163}
1164
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001165status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 audio_stream_type_t stream,
1167 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001168 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001169 uint32_t *delayMs)
1170{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001171 // cannot start playback of STREAM_TTS if any other output is being used
1172 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001173
1174 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001175 if (stream == AUDIO_STREAM_TTS) {
1176 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001177 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001178 return INVALID_OPERATION;
1179 } else {
1180 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1181 }
1182 } else {
1183 // some playback other than beacon starts
1184 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1185 }
1186
Eric Laurent77305a62016-07-25 16:39:22 -07001187 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001188 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001189 bool force = !outputDesc->isActive() &&
1190 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001191
Eric Laurente552edb2014-03-10 17:42:56 -07001192 // increment usage count for this stream on the requested output:
1193 // NOTE that the usage count is the same for duplicated output and hardware output which is
1194 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1195 outputDesc->changeRefCount(stream, 1);
1196
Eric Laurent493404d2015-04-21 15:07:36 -07001197 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001198 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001199 if (device == AUDIO_DEVICE_NONE) {
1200 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001201 }
Eric Laurente552edb2014-03-10 17:42:56 -07001202 routing_strategy strategy = getStrategy(stream);
1203 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001204 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1205 (beaconMuteLatency > 0);
1206 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001207 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001208 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001209 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001210 // force a device change if any other output is:
1211 // - managed by the same hw module
1212 // - has a current device selection that differs from selected device.
1213 // - supports currently selected device
1214 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001215 // In this case, the audio HAL must receive the new device selection so that it can
1216 // change the device currently selected by the other active output.
1217 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001218 desc->device() != device &&
1219 desc->supportedDevices() & device &&
1220 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001221 force = true;
1222 }
1223 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001224 // a notification so that audio focus effect can propagate, or that a mute/unmute
1225 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001226 uint32_t latency = desc->latency();
1227 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1228 waitMs = latency;
1229 }
1230 }
1231 }
Eric Laurentdc462862016-07-19 12:29:53 -07001232 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001233
1234 // handle special case for sonification while in call
1235 if (isInCall()) {
1236 handleIncallSonification(stream, true, false);
1237 }
1238
1239 // apply volume rules for current stream and device if necessary
1240 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001241 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001242 outputDesc,
1243 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001244
1245 // update the outputs if starting an output with a stream that can affect notification
1246 // routing
1247 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001248
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001249 // force reevaluating accessibility routing when ringtone or alarm starts
1250 if (strategy == STRATEGY_SONIFICATION) {
1251 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1252 }
Eric Laurentdc462862016-07-19 12:29:53 -07001253
1254 if (waitMs > muteWaitMs) {
1255 *delayMs = waitMs - muteWaitMs;
1256 }
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
Eric Laurentdc462862016-07-19 12:29:53 -07001258
Eric Laurente552edb2014-03-10 17:42:56 -07001259 return NO_ERROR;
1260}
1261
1262
Eric Laurente0720872014-03-11 09:30:41 -07001263status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001264 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001265 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001266{
1267 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1268 ssize_t index = mOutputs.indexOfKey(output);
1269 if (index < 0) {
1270 ALOGW("stopOutput() unknown output %d", output);
1271 return BAD_VALUE;
1272 }
1273
Eric Laurentc75307b2015-03-17 15:29:32 -07001274 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001275
Eric Laurentc75307b2015-03-17 15:29:32 -07001276 if (outputDesc->mRefCount[stream] == 1) {
1277 // Automatically disable the remote submix input when output is stopped on a
1278 // re routing mix of type MIX_TYPE_RECORDERS
1279 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1280 outputDesc->mPolicyMix != NULL &&
1281 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1282 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1283 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001284 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001285 "remote-submix");
1286 }
1287 }
1288
1289 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001290 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001291 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001292 int activityCount = mOutputRoutes.decRouteActivity(session);
1293 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1294
1295 if (forceDeviceUpdate) {
1296 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1297 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001298 }
1299
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001300 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001301}
1302
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001303status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001304 audio_stream_type_t stream,
1305 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001306{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001307 // always handle stream stop, check which stream type is stopping
1308 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1309
Eric Laurente552edb2014-03-10 17:42:56 -07001310 // handle special case for sonification while in call
1311 if (isInCall()) {
1312 handleIncallSonification(stream, false, false);
1313 }
1314
1315 if (outputDesc->mRefCount[stream] > 0) {
1316 // decrement usage count of this stream on the output
1317 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001318
Eric Laurente552edb2014-03-10 17:42:56 -07001319 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001320 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001321 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001322 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001323 // delay the device switch by twice the latency because stopOutput() is executed when
1324 // the track stop() command is received and at that time the audio track buffer can
1325 // still contain data that needs to be drained. The latency only covers the audio HAL
1326 // and kernel buffers. Also the latency does not always include additional delay in the
1327 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001328 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001329
1330 // force restoring the device selection on other active outputs if it differs from the
1331 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001332 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001333 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001334 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001335 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001336 desc->isActive() &&
1337 outputDesc->sharesHwModuleWith(desc) &&
1338 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001339 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1340 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001341 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001342 newDevice2,
1343 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001344 delayMs);
1345 // re-apply device specific volume if not done by setOutputDevice()
1346 if (!force) {
1347 applyStreamVolumes(desc, newDevice2, delayMs);
1348 }
Eric Laurente552edb2014-03-10 17:42:56 -07001349 }
1350 }
1351 // update the outputs if stopping one with a stream that can affect notification routing
1352 handleNotificationRoutingForStream(stream);
1353 }
1354 return NO_ERROR;
1355 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001356 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001357 return INVALID_OPERATION;
1358 }
1359}
1360
Eric Laurente83b55d2014-11-14 10:06:21 -08001361void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001362 audio_stream_type_t stream __unused,
1363 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001364{
1365 ALOGV("releaseOutput() %d", output);
1366 ssize_t index = mOutputs.indexOfKey(output);
1367 if (index < 0) {
1368 ALOGW("releaseOutput() releasing unknown output %d", output);
1369 return;
1370 }
1371
1372#ifdef AUDIO_POLICY_TEST
1373 int testIndex = testOutputIndex(output);
1374 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001375 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001376 if (outputDesc->isActive()) {
1377 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001378 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 mTestOutputs[testIndex] = 0;
1380 }
1381 return;
1382 }
1383#endif //AUDIO_POLICY_TEST
1384
Paul McLeanaa981192015-03-21 09:55:15 -07001385 // Routing
1386 mOutputRoutes.removeRoute(session);
1387
Eric Laurentc75307b2015-03-17 15:29:32 -07001388 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001389 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001390 if (desc->mDirectOpenCount <= 0) {
1391 ALOGW("releaseOutput() invalid open count %d for output %d",
1392 desc->mDirectOpenCount, output);
1393 return;
1394 }
1395 if (--desc->mDirectOpenCount == 0) {
1396 closeOutput(output);
1397 // If effects where present on the output, audioflinger moved them to the primary
1398 // output by default: move them back to the appropriate output.
1399 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001400 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001401 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1402 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001403 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001404 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001405 }
1406 }
1407}
1408
1409
Eric Laurentcaf7f482014-11-25 17:50:47 -08001410status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1411 audio_io_handle_t *input,
1412 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001413 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001414 uint32_t samplingRate,
1415 audio_format_t format,
1416 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001417 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001418 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001419 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001420{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001421 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1422 "session %d, flags %#x",
1423 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001424
Eric Laurentcaf7f482014-11-25 17:50:47 -08001425 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001426 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001427
Eric Laurent275e8e92014-11-30 15:14:47 -08001428 audio_devices_t device;
1429 // handle legacy remote submix case where the address was not always specified
1430 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001431 audio_source_t inputSource = attr->source;
1432 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001433 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001434
Eric Laurentc447ded2015-01-06 08:47:05 -08001435 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1436 inputSource = AUDIO_SOURCE_MIC;
1437 }
1438 halInputSource = inputSource;
1439
Paul McLean466dc8e2015-04-17 13:15:36 -06001440 // Explicit routing?
1441 sp<DeviceDescriptor> deviceDesc;
1442 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1443 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1444 deviceDesc = mAvailableInputDevices[i];
1445 break;
1446 }
1447 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001448 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001449
Eric Laurentc447ded2015-01-06 08:47:05 -08001450 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001451 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001452 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001453 if (ret != NO_ERROR) {
1454 return ret;
1455 }
1456 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001457 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1458 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001459 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001460 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001462 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001463 return BAD_VALUE;
1464 }
Eric Laurentc722f302014-12-10 11:21:49 -08001465 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001466 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001467 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1468 // there is an external policy, but this input is attached to a mix of recorders,
1469 // meaning it receives audio injected into the framework, so the recorder doesn't
1470 // know about it and is therefore considered "legacy"
1471 *inputType = API_INPUT_LEGACY;
1472 } else {
1473 // recording a mix of players defined by an external policy, we're rerouting for
1474 // an external policy
1475 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1476 }
Eric Laurentc722f302014-12-10 11:21:49 -08001477 } else if (audio_is_remote_submix_device(device)) {
1478 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001479 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001480 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1481 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001482 } else {
1483 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001484 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001485
Eric Laurent599c7582015-12-07 18:05:55 -08001486 }
1487
1488 *input = getInputForDevice(device, address, session, uid, inputSource,
1489 samplingRate, format, channelMask, flags,
1490 policyMix);
1491 if (*input == AUDIO_IO_HANDLE_NONE) {
1492 mInputRoutes.removeRoute(session);
1493 return INVALID_OPERATION;
1494 }
1495 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1496 return NO_ERROR;
1497}
1498
1499
1500audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1501 String8 address,
1502 audio_session_t session,
1503 uid_t uid,
1504 audio_source_t inputSource,
1505 uint32_t samplingRate,
1506 audio_format_t format,
1507 audio_channel_mask_t channelMask,
1508 audio_input_flags_t flags,
1509 AudioMix *policyMix)
1510{
1511 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1512 audio_source_t halInputSource = inputSource;
1513 bool isSoundTrigger = false;
1514
1515 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1516 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1517 if (index >= 0) {
1518 input = mSoundTriggerSessions.valueFor(session);
1519 isSoundTrigger = true;
1520 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1521 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1522 } else {
1523 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001524 }
1525 }
1526
Andy Hungf129b032015-04-07 13:45:50 -07001527 // find a compatible input profile (not necessarily identical in parameters)
1528 sp<IOProfile> profile;
1529 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001530 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001531 audio_format_t profileFormat = format;
1532 audio_channel_mask_t profileChannelMask = channelMask;
1533 audio_input_flags_t profileFlags = flags;
1534 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001535 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001536 profileSamplingRate, profileFormat, profileChannelMask,
1537 profileFlags);
1538 if (profile != 0) {
1539 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001540 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1541 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001542 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1543 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1544 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001545 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1546 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001547 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001548 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001549 }
Eric Laurente552edb2014-03-10 17:42:56 -07001550 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001551 // Pick input sampling rate if not specified by client
1552 if (samplingRate == 0) {
1553 samplingRate = profileSamplingRate;
1554 }
Eric Laurente552edb2014-03-10 17:42:56 -07001555
Eric Laurent322b4d22015-04-03 15:57:54 -07001556 if (profile->getModuleHandle() == 0) {
1557 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001558 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001559 }
1560
Eric Laurent599c7582015-12-07 18:05:55 -08001561 sp<AudioSession> audioSession = new AudioSession(session,
1562 inputSource,
1563 format,
1564 samplingRate,
1565 channelMask,
1566 flags,
1567 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001568 isSoundTrigger,
1569 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001570
Eric Laurentfb66dd92016-01-28 18:32:03 -08001571
Eric Laurent599c7582015-12-07 18:05:55 -08001572 // reuse an open input if possible
1573 for (size_t i = 0; i < mInputs.size(); i++) {
1574 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001575 // reuse input if:
1576 // - it shares the same profile
1577 // AND
1578 // - it is not a reroute submix input
1579 // AND
1580 // - it is: not used for sound trigger
1581 // OR
1582 // used for sound trigger and all clients use the same session ID
1583 //
1584 if ((profile == desc->mProfile) &&
1585 (isSoundTrigger == desc->isSoundTrigger()) &&
1586 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001587
1588 sp<AudioSession> as = desc->getAudioSession(session);
1589 if (as != 0) {
1590 // do not allow unmatching properties on same session
1591 if (as->matches(audioSession)) {
1592 as->changeOpenCount(1);
1593 } else {
1594 ALOGW("getInputForDevice() record with different attributes"
1595 " exists for session %d", session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001596 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001597 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001598 } else if (isSoundTrigger) {
1599 break;
1600 }
1601 // force close input if current source is now the highest priority request on this input
1602 // and current input properties are not exactly as requested.
1603 if ((desc->mSamplingRate != samplingRate ||
1604 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001605 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001606 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
1607 source_priority(inputSource))) {
1608 ALOGV("%s: ", __FUNCTION__);
1609 AudioSessionCollection sessions = desc->getAudioSessions(false /*activeOnly*/);
1610 for (size_t j = 0; j < sessions.size(); j++) {
1611 audio_session_t currentSession = sessions.keyAt(j);
1612 stopInput(desc->mIoHandle, currentSession);
1613 releaseInput(desc->mIoHandle, currentSession);
1614 }
1615 break;
Eric Laurent599c7582015-12-07 18:05:55 -08001616 } else {
1617 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001618 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1619 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001620 }
Eric Laurent599c7582015-12-07 18:05:55 -08001621 }
1622 }
Eric Laurent599c7582015-12-07 18:05:55 -08001623
Eric Laurentcf2c0212014-07-25 16:20:43 -07001624 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001625 config.sample_rate = profileSamplingRate;
1626 config.channel_mask = profileChannelMask;
1627 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001628
Eric Laurent322b4d22015-04-03 15:57:54 -07001629 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001630 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001631 &config,
1632 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001633 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001634 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001635 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001636
1637 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001638 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001639 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001640 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001641 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001642 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1643 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001644 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001645 if (input != AUDIO_IO_HANDLE_NONE) {
1646 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001647 }
Eric Laurent599c7582015-12-07 18:05:55 -08001648 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001649 }
1650
Eric Laurent1f2f2232014-06-02 12:01:23 -07001651 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001652 inputDesc->mSamplingRate = profileSamplingRate;
1653 inputDesc->mFormat = profileFormat;
1654 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001655 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001656 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001657 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001658
Eric Laurent599c7582015-12-07 18:05:55 -08001659 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001660 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001661
Eric Laurent599c7582015-12-07 18:05:55 -08001662 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001663}
1664
Eric Laurentfb66dd92016-01-28 18:32:03 -08001665bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1666 const sp<AudioSession>& audioSession)
1667{
1668 // Do not allow capture if an active voice call is using a software patch and
1669 // the call TX source device is on the same HW module.
1670 // FIXME: would be better to refine to only inputs whose profile connects to the
1671 // call TX device but this information is not in the audio patch
1672 if (mCallTxPatch != 0 &&
1673 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1674 return false;
1675 }
1676
1677 // starting concurrent capture is enabled if:
1678 // 1) capturing for re-routing
1679 // 2) capturing for HOTWORD source
1680 // 3) capturing for FM TUNER source
1681 // 3) All other active captures are either for re-routing or HOTWORD
1682
1683 if (is_virtual_input_device(inputDesc->mDevice) ||
1684 audioSession->inputSource() == AUDIO_SOURCE_HOTWORD ||
1685 audioSession->inputSource() == AUDIO_SOURCE_FM_TUNER) {
1686 return true;
1687 }
1688
1689 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1690 for (size_t i = 0; i < activeInputs.size(); i++) {
1691 sp<AudioInputDescriptor> activeInput = activeInputs[i];
1692 if ((activeInput->inputSource() != AUDIO_SOURCE_HOTWORD) &&
1693 (activeInput->inputSource() != AUDIO_SOURCE_FM_TUNER) &&
1694 !is_virtual_input_device(activeInput->mDevice)) {
1695 return false;
1696 }
1697 }
1698
1699 return true;
1700}
1701
1702
Eric Laurent4dc68062014-07-28 17:26:49 -07001703status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001704 audio_session_t session,
1705 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001706{
1707 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001708 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001709 ssize_t index = mInputs.indexOfKey(input);
1710 if (index < 0) {
1711 ALOGW("startInput() unknown input %d", input);
1712 return BAD_VALUE;
1713 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001714 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent599c7582015-12-07 18:05:55 -08001716 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1717 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001718 ALOGW("startInput() unknown session %d on input %d", session, input);
1719 return BAD_VALUE;
1720 }
1721
Eric Laurentfb66dd92016-01-28 18:32:03 -08001722 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1723 ALOGW("startInput(%d) failed: other input already started", input);
1724 return INVALID_OPERATION;
1725 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001726
Eric Laurentfb66dd92016-01-28 18:32:03 -08001727 if (isInCall()) {
1728 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1729 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001730 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001731 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001732 }
1733
Eric Laurent313d1e72016-01-29 09:56:57 -08001734 // increment activity count before calling getNewInputDevice() below as only active sessions
1735 // are considered for device selection
1736 audioSession->changeActiveCount(1);
1737
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001738 // Routing?
1739 mInputRoutes.incRouteActivity(session);
1740
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001741 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001742 // indicate active capture to sound trigger service if starting capture from a mic on
1743 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001744 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001745 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001746
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001747 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1748 // if input maps to a dynamic policy with an activity listener, notify of state change
1749 if ((inputDesc->mPolicyMix != NULL)
1750 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1751 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1752 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001753 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001754
Eric Laurentf7c50102016-09-30 15:19:43 -07001755 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1756 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001757 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001758 SoundTrigger::setCaptureState(true);
1759 }
1760
1761 // automatically enable the remote submix output when input is started if not
1762 // used by a policy mix of type MIX_TYPE_RECORDERS
1763 // For remote submix (a virtual device), we open only one input per capture request.
1764 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1765 String8 address = String8("");
1766 if (inputDesc->mPolicyMix == NULL) {
1767 address = String8("0");
1768 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1769 address = inputDesc->mPolicyMix->mDeviceAddress;
1770 }
1771 if (address != "") {
1772 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1774 address, "remote-submix");
1775 }
Eric Laurentc722f302014-12-10 11:21:49 -08001776 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001777 }
Eric Laurente552edb2014-03-10 17:42:56 -07001778 }
1779
Eric Laurent599c7582015-12-07 18:05:55 -08001780 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001781
Eric Laurente552edb2014-03-10 17:42:56 -07001782 return NO_ERROR;
1783}
1784
Eric Laurent4dc68062014-07-28 17:26:49 -07001785status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1786 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001787{
1788 ALOGV("stopInput() input %d", input);
1789 ssize_t index = mInputs.indexOfKey(input);
1790 if (index < 0) {
1791 ALOGW("stopInput() unknown input %d", input);
1792 return BAD_VALUE;
1793 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001794 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001795
Eric Laurent599c7582015-12-07 18:05:55 -08001796 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001797 if (index < 0) {
1798 ALOGW("stopInput() unknown session %d on input %d", session, input);
1799 return BAD_VALUE;
1800 }
1801
Eric Laurent599c7582015-12-07 18:05:55 -08001802 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001803 ALOGW("stopInput() input %d already stopped", input);
1804 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001805 }
1806
Eric Laurent599c7582015-12-07 18:05:55 -08001807 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001808
1809 // Routing?
1810 mInputRoutes.decRouteActivity(session);
1811
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001812 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001813
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001814 if (inputDesc->isActive()) {
1815 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1816 } else {
1817 // if input maps to a dynamic policy with an activity listener, notify of state change
1818 if ((inputDesc->mPolicyMix != NULL)
1819 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1820 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1821 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001822 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001823
1824 // automatically disable the remote submix output when input is stopped if not
1825 // used by a policy mix of type MIX_TYPE_RECORDERS
1826 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1827 String8 address = String8("");
1828 if (inputDesc->mPolicyMix == NULL) {
1829 address = String8("0");
1830 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1831 address = inputDesc->mPolicyMix->mDeviceAddress;
1832 }
1833 if (address != "") {
1834 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1835 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1836 address, "remote-submix");
1837 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001838 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001839
Eric Laurentf7c50102016-09-30 15:19:43 -07001840 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001841 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001842
Eric Laurentf7c50102016-09-30 15:19:43 -07001843 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1844 // primary HW module
1845 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1846 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1847 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001848 SoundTrigger::setCaptureState(false);
1849 }
1850 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001851 }
Eric Laurente552edb2014-03-10 17:42:56 -07001852 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001853 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001854}
1855
Eric Laurent4dc68062014-07-28 17:26:49 -07001856void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1857 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001858{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001859
Eric Laurente552edb2014-03-10 17:42:56 -07001860 ALOGV("releaseInput() %d", input);
1861 ssize_t index = mInputs.indexOfKey(input);
1862 if (index < 0) {
1863 ALOGW("releaseInput() releasing unknown input %d", input);
1864 return;
1865 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001866
1867 // Routing
1868 mInputRoutes.removeRoute(session);
1869
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001870 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1871 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001872
Eric Laurent599c7582015-12-07 18:05:55 -08001873 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001874 if (index < 0) {
1875 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1876 return;
1877 }
Eric Laurent599c7582015-12-07 18:05:55 -08001878
1879 if (audioSession->openCount() == 0) {
1880 ALOGW("releaseInput() invalid open count %d on session %d",
1881 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001882 return;
1883 }
Eric Laurent599c7582015-12-07 18:05:55 -08001884
1885 if (audioSession->changeOpenCount(-1) == 0) {
1886 inputDesc->removeAudioSession(session);
1887 }
1888
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001889 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001890 ALOGV("releaseInput() exit > 0");
1891 return;
1892 }
1893
Eric Laurent05b90f82014-08-27 15:32:29 -07001894 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001895 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001896 ALOGV("releaseInput() exit");
1897}
1898
Eric Laurentd4692962014-05-05 18:13:44 -07001899void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001900 bool patchRemoved = false;
1901
Eric Laurentd4692962014-05-05 18:13:44 -07001902 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001903 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001904 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001905 if (patch_index >= 0) {
1906 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001907 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001908 mAudioPatches.removeItemsAt(patch_index);
1909 patchRemoved = true;
1910 }
Eric Laurentd4692962014-05-05 18:13:44 -07001911 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1912 }
1913 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001914 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001915 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001916
1917 if (patchRemoved) {
1918 mpClientInterface->onAudioPatchListUpdate();
1919 }
Eric Laurentd4692962014-05-05 18:13:44 -07001920}
1921
Eric Laurente0720872014-03-11 09:30:41 -07001922void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001923 int indexMin,
1924 int indexMax)
1925{
1926 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001927 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001928
1929 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001930 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1931 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001932 continue;
1933 }
1934 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001935 }
Eric Laurente552edb2014-03-10 17:42:56 -07001936}
1937
Eric Laurente0720872014-03-11 09:30:41 -07001938status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001939 int index,
1940 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001941{
1942
François Gaffied1ab2bd2015-12-02 18:20:06 +01001943 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1944 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001945 return BAD_VALUE;
1946 }
1947 if (!audio_is_output_device(device)) {
1948 return BAD_VALUE;
1949 }
1950
1951 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001952 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001953
Eric Laurent1fd372e2016-04-06 14:23:53 -07001954 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001955 stream, device, index);
1956
Eric Laurent28d09f02016-03-08 10:43:05 -08001957 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001958 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1959 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001960 continue;
1961 }
1962 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1963 }
Eric Laurente552edb2014-03-10 17:42:56 -07001964
Eric Laurent1fd372e2016-04-06 14:23:53 -07001965 // update volume on all outputs and streams matching the following:
1966 // - The requested stream (or a stream matching for volume control) is active on the output
1967 // - The device (or devices) selected by the strategy corresponding to this stream includes
1968 // the requested device
1969 // - For non default requested device, currently selected device on the output is either the
1970 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001971 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1972 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001973 status_t status = NO_ERROR;
1974 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001975 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1976 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001977 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1978 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001979 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001980 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001981 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1982 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001983 continue;
1984 }
Eric Laurent794fde22016-03-11 09:50:45 -08001985 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07001986 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
1987 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
1988 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001989 continue;
1990 }
Eric Laurente76f29c2016-09-14 17:17:53 -07001991 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001992 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001993 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07001994 applyVolume = (curDevice & curStreamDevice) != 0;
1995 } else {
1996 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
1997 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07001998 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001999
Eric Laurente76f29c2016-09-14 17:17:53 -07002000 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002001 //FIXME: workaround for truncated touch sounds
2002 // delayed volume change for system stream to be removed when the problem is
2003 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002004 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002005 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2006 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002007 if (volStatus != NO_ERROR) {
2008 status = volStatus;
2009 }
2010 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002011 }
Eric Laurente552edb2014-03-10 17:42:56 -07002012 }
2013 return status;
2014}
2015
Eric Laurente0720872014-03-11 09:30:41 -07002016status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002017 int *index,
2018 audio_devices_t device)
2019{
2020 if (index == NULL) {
2021 return BAD_VALUE;
2022 }
2023 if (!audio_is_output_device(device)) {
2024 return BAD_VALUE;
2025 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002026 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002027 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002028 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002029 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2030 }
François Gaffiedfd74092015-03-19 12:10:59 +01002031 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002032
François Gaffied1ab2bd2015-12-02 18:20:06 +01002033 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002034 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2035 return NO_ERROR;
2036}
2037
Eric Laurente0720872014-03-11 09:30:41 -07002038audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002039 const SortedVector<audio_io_handle_t>& outputs)
2040{
2041 // select one output among several suitable for global effects.
2042 // The priority is as follows:
2043 // 1: An offloaded output. If the effect ends up not being offloadable,
2044 // AudioFlinger will invalidate the track and the offloaded output
2045 // will be closed causing the effect to be moved to a PCM output.
2046 // 2: A deep buffer output
2047 // 3: the first output in the list
2048
2049 if (outputs.size() == 0) {
2050 return 0;
2051 }
2052
2053 audio_io_handle_t outputOffloaded = 0;
2054 audio_io_handle_t outputDeepBuffer = 0;
2055
2056 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002057 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002058 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002059 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2060 outputOffloaded = outputs[i];
2061 }
2062 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2063 outputDeepBuffer = outputs[i];
2064 }
2065 }
2066
2067 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2068 outputOffloaded, outputDeepBuffer);
2069 if (outputOffloaded != 0) {
2070 return outputOffloaded;
2071 }
2072 if (outputDeepBuffer != 0) {
2073 return outputDeepBuffer;
2074 }
2075
2076 return outputs[0];
2077}
2078
Eric Laurente0720872014-03-11 09:30:41 -07002079audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002080{
2081 // apply simple rule where global effects are attached to the same output as MUSIC streams
2082
Eric Laurent3b73df72014-03-11 09:06:29 -07002083 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002084 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2085 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2086
2087 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2088 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2089 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2090
2091 return output;
2092}
2093
Eric Laurente0720872014-03-11 09:30:41 -07002094status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002095 audio_io_handle_t io,
2096 uint32_t strategy,
2097 int session,
2098 int id)
2099{
2100 ssize_t index = mOutputs.indexOfKey(io);
2101 if (index < 0) {
2102 index = mInputs.indexOfKey(io);
2103 if (index < 0) {
2104 ALOGW("registerEffect() unknown io %d", io);
2105 return INVALID_OPERATION;
2106 }
2107 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002108 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002109}
2110
Eric Laurentc75307b2015-03-17 15:29:32 -07002111bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2112{
Eric Laurent28d09f02016-03-08 10:43:05 -08002113 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002114 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2115 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002116 continue;
2117 }
2118 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2119 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002120 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002121}
2122
2123bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2124{
2125 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2126}
2127
Eric Laurente0720872014-03-11 09:30:41 -07002128bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002129{
2130 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002131 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002132 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002133 return true;
2134 }
2135 }
2136 return false;
2137}
2138
Eric Laurent275e8e92014-11-30 15:14:47 -08002139// Register a list of custom mixes with their attributes and format.
2140// When a mix is registered, corresponding input and output profiles are
2141// added to the remote submix hw module. The profile contains only the
2142// parameters (sampling rate, format...) specified by the mix.
2143// The corresponding input remote submix device is also connected.
2144//
2145// When a remote submix device is connected, the address is checked to select the
2146// appropriate profile and the corresponding input or output stream is opened.
2147//
2148// When capture starts, getInputForAttr() will:
2149// - 1 look for a mix matching the address passed in attribtutes tags if any
2150// - 2 if none found, getDeviceForInputSource() will:
2151// - 2.1 look for a mix matching the attributes source
2152// - 2.2 if none found, default to device selection by policy rules
2153// At this time, the corresponding output remote submix device is also connected
2154// and active playback use cases can be transferred to this mix if needed when reconnecting
2155// after AudioTracks are invalidated
2156//
2157// When playback starts, getOutputForAttr() will:
2158// - 1 look for a mix matching the address passed in attribtutes tags if any
2159// - 2 if none found, look for a mix matching the attributes usage
2160// - 3 if none found, default to device and output selection by policy rules.
2161
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002162status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002163{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002164 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2165 status_t res = NO_ERROR;
2166
2167 sp<HwModule> rSubmixModule;
2168 // examine each mix's route type
2169 for (size_t i = 0; i < mixes.size(); i++) {
2170 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2171 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2172 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002173 break;
2174 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002175 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2176 // Loop back through "remote submix"
2177 if (rSubmixModule == 0) {
2178 for (size_t j = 0; i < mHwModules.size(); j++) {
2179 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2180 && mHwModules[j]->mHandle != 0) {
2181 rSubmixModule = mHwModules[j];
2182 break;
2183 }
2184 }
2185 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002186
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002187 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002188
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002189 if (rSubmixModule == 0) {
2190 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2191 res = INVALID_OPERATION;
2192 break;
2193 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002194
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002195 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002196
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002197 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002198 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002199 res = INVALID_OPERATION;
2200 break;
2201 }
2202 audio_config_t outputConfig = mixes[i].mFormat;
2203 audio_config_t inputConfig = mixes[i].mFormat;
2204 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2205 // stereo and let audio flinger do the channel conversion if needed.
2206 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2207 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2208 rSubmixModule->addOutputProfile(address, &outputConfig,
2209 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2210 rSubmixModule->addInputProfile(address, &inputConfig,
2211 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002212
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002213 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2214 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2215 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2216 address.string(), "remote-submix");
2217 } else {
2218 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2219 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2220 address.string(), "remote-submix");
2221 }
2222 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002223 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002224 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002225 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2226 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002227
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002228 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002229 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2230 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2231 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2232 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2233 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2234 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002235 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2236 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002237 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2238 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002239 } else {
2240 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002241 }
2242 break;
2243 }
2244 }
2245
2246 if (res != NO_ERROR) {
2247 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002248 i, device, address.string());
2249 res = INVALID_OPERATION;
2250 break;
2251 } else if (!foundOutput) {
2252 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2253 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002254 res = INVALID_OPERATION;
2255 break;
2256 }
Eric Laurentc722f302014-12-10 11:21:49 -08002257 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002258 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002259 if (res != NO_ERROR) {
2260 unregisterPolicyMixes(mixes);
2261 }
2262 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002263}
2264
2265status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2266{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002267 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002268 status_t res = NO_ERROR;
2269 sp<HwModule> rSubmixModule;
2270 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002271 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002272 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002273
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002274 if (rSubmixModule == 0) {
2275 for (size_t j = 0; i < mHwModules.size(); j++) {
2276 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2277 && mHwModules[j]->mHandle != 0) {
2278 rSubmixModule = mHwModules[j];
2279 break;
2280 }
2281 }
2282 }
2283 if (rSubmixModule == 0) {
2284 res = INVALID_OPERATION;
2285 continue;
2286 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002287
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002288 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002289
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002290 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2291 res = INVALID_OPERATION;
2292 continue;
2293 }
2294
2295 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2296 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2297 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2298 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2299 address.string(), "remote-submix");
2300 }
2301 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2302 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2303 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2304 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2305 address.string(), "remote-submix");
2306 }
2307 rSubmixModule->removeOutputProfile(address);
2308 rSubmixModule->removeInputProfile(address);
2309
2310 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2311 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2312 res = INVALID_OPERATION;
2313 continue;
2314 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002315 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002316 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002317 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002318}
2319
Eric Laurente552edb2014-03-10 17:42:56 -07002320
Eric Laurente0720872014-03-11 09:30:41 -07002321status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002322{
2323 const size_t SIZE = 256;
2324 char buffer[SIZE];
2325 String8 result;
2326
2327 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2328 result.append(buffer);
2329
Eric Laurent87ffa392015-05-22 10:32:38 -07002330 snprintf(buffer, SIZE, " Primary Output: %d\n",
2331 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002333 std::string stateLiteral;
2334 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2335 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002336 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002337 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002338 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002339 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002340 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002341 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002342 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002343 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002344 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002345 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002346 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002347 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002348 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002349 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002350 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002351 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2352 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2353 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002354 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2355 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002356 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2357 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002358
François Gaffie2110e042015-03-24 08:41:51 +01002359 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002360
François Gaffie112b0af2015-11-19 16:13:25 +01002361 mAvailableOutputDevices.dump(fd, String8("Available output"));
2362 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002363 mHwModules.dump(fd);
2364 mOutputs.dump(fd);
2365 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002366 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002367 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002368 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002369
2370 return NO_ERROR;
2371}
2372
2373// This function checks for the parameters which can be offloaded.
2374// This can be enhanced depending on the capability of the DSP and policy
2375// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002376bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002377{
2378 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002379 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002380 offloadInfo.sample_rate, offloadInfo.channel_mask,
2381 offloadInfo.format,
2382 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2383 offloadInfo.has_video);
2384
Andy Hung2ddee192015-12-18 17:34:44 -08002385 if (mMasterMono) {
2386 return false; // no offloading if mono is set.
2387 }
2388
Eric Laurente552edb2014-03-10 17:42:56 -07002389 // Check if offload has been disabled
2390 char propValue[PROPERTY_VALUE_MAX];
2391 if (property_get("audio.offload.disable", propValue, "0")) {
2392 if (atoi(propValue) != 0) {
2393 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2394 return false;
2395 }
2396 }
2397
2398 // Check if stream type is music, then only allow offload as of now.
2399 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2400 {
2401 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2402 return false;
2403 }
2404
2405 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002406 const bool allowOffloadWithVideo =
2407 property_get_bool("audio.offload.video", false /* default_value */);
2408 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002409 ALOGV("isOffloadSupported: has_video == true, returning false");
2410 return false;
2411 }
2412
2413 //If duration is less than minimum value defined in property, return false
2414 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2415 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2416 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2417 return false;
2418 }
2419 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2420 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2421 return false;
2422 }
2423
2424 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2425 // creating an offloaded track and tearing it down immediately after start when audioflinger
2426 // detects there is an active non offloadable effect.
2427 // FIXME: We should check the audio session here but we do not have it in this context.
2428 // This may prevent offloading in rare situations where effects are left active by apps
2429 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002430 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002431 return false;
2432 }
2433
2434 // See if there is a profile to support this.
2435 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002436 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002437 offloadInfo.sample_rate,
2438 offloadInfo.format,
2439 offloadInfo.channel_mask,
2440 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002441 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2442 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002443}
2444
Eric Laurent6a94d692014-05-20 11:18:06 -07002445status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2446 audio_port_type_t type,
2447 unsigned int *num_ports,
2448 struct audio_port *ports,
2449 unsigned int *generation)
2450{
2451 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2452 generation == NULL) {
2453 return BAD_VALUE;
2454 }
2455 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2456 if (ports == NULL) {
2457 *num_ports = 0;
2458 }
2459
2460 size_t portsWritten = 0;
2461 size_t portsMax = *num_ports;
2462 *num_ports = 0;
2463 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002464 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2465 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002466 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002467 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2468 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2469 continue;
2470 }
2471 if (portsWritten < portsMax) {
2472 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2473 }
2474 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002475 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002476 }
2477 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002478 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2479 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2480 continue;
2481 }
2482 if (portsWritten < portsMax) {
2483 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2484 }
2485 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002486 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002487 }
2488 }
2489 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2490 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2491 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2492 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2493 }
2494 *num_ports += mInputs.size();
2495 }
2496 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002497 size_t numOutputs = 0;
2498 for (size_t i = 0; i < mOutputs.size(); i++) {
2499 if (!mOutputs[i]->isDuplicated()) {
2500 numOutputs++;
2501 if (portsWritten < portsMax) {
2502 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2503 }
2504 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002505 }
Eric Laurent84c70242014-06-23 08:46:27 -07002506 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002507 }
2508 }
2509 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002510 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002511 return NO_ERROR;
2512}
2513
2514status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2515{
2516 return NO_ERROR;
2517}
2518
Eric Laurent6a94d692014-05-20 11:18:06 -07002519status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2520 audio_patch_handle_t *handle,
2521 uid_t uid)
2522{
2523 ALOGV("createAudioPatch()");
2524
2525 if (handle == NULL || patch == NULL) {
2526 return BAD_VALUE;
2527 }
2528 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2529
Eric Laurent874c42872014-08-08 15:13:39 -07002530 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2531 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2532 return BAD_VALUE;
2533 }
2534 // only one source per audio patch supported for now
2535 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002536 return INVALID_OPERATION;
2537 }
Eric Laurent874c42872014-08-08 15:13:39 -07002538
2539 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002540 return INVALID_OPERATION;
2541 }
Eric Laurent874c42872014-08-08 15:13:39 -07002542 for (size_t i = 0; i < patch->num_sinks; i++) {
2543 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2544 return INVALID_OPERATION;
2545 }
2546 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002547
2548 sp<AudioPatch> patchDesc;
2549 ssize_t index = mAudioPatches.indexOfKey(*handle);
2550
Eric Laurent6a94d692014-05-20 11:18:06 -07002551 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2552 patch->sources[0].role,
2553 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002554#if LOG_NDEBUG == 0
2555 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002556 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002557 patch->sinks[i].role,
2558 patch->sinks[i].type);
2559 }
2560#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002561
2562 if (index >= 0) {
2563 patchDesc = mAudioPatches.valueAt(index);
2564 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2565 mUidCached, patchDesc->mUid, uid);
2566 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2567 return INVALID_OPERATION;
2568 }
2569 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002570 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002571 }
2572
2573 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002574 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002575 if (outputDesc == NULL) {
2576 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2577 return BAD_VALUE;
2578 }
Eric Laurent84c70242014-06-23 08:46:27 -07002579 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2580 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002581 if (patchDesc != 0) {
2582 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2583 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2584 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2585 return BAD_VALUE;
2586 }
2587 }
Eric Laurent874c42872014-08-08 15:13:39 -07002588 DeviceVector devices;
2589 for (size_t i = 0; i < patch->num_sinks; i++) {
2590 // Only support mix to devices connection
2591 // TODO add support for mix to mix connection
2592 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2593 ALOGV("createAudioPatch() source mix but sink is not a device");
2594 return INVALID_OPERATION;
2595 }
2596 sp<DeviceDescriptor> devDesc =
2597 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2598 if (devDesc == 0) {
2599 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2600 return BAD_VALUE;
2601 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002602
François Gaffie53615e22015-03-19 09:24:12 +01002603 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002604 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002605 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002606 NULL, // updatedSamplingRate
2607 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002608 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002609 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002610 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002611 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002612 ALOGV("createAudioPatch() profile not supported for device %08x",
2613 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002614 return INVALID_OPERATION;
2615 }
2616 devices.add(devDesc);
2617 }
2618 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002619 return INVALID_OPERATION;
2620 }
Eric Laurent874c42872014-08-08 15:13:39 -07002621
Eric Laurent6a94d692014-05-20 11:18:06 -07002622 // TODO: reconfigure output format and channels here
2623 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002624 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002625 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002626 index = mAudioPatches.indexOfKey(*handle);
2627 if (index >= 0) {
2628 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2629 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2630 }
2631 patchDesc = mAudioPatches.valueAt(index);
2632 patchDesc->mUid = uid;
2633 ALOGV("createAudioPatch() success");
2634 } else {
2635 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2636 return INVALID_OPERATION;
2637 }
2638 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2639 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2640 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002641 // only one sink supported when connecting an input device to a mix
2642 if (patch->num_sinks > 1) {
2643 return INVALID_OPERATION;
2644 }
François Gaffie53615e22015-03-19 09:24:12 +01002645 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002646 if (inputDesc == NULL) {
2647 return BAD_VALUE;
2648 }
2649 if (patchDesc != 0) {
2650 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2651 return BAD_VALUE;
2652 }
2653 }
2654 sp<DeviceDescriptor> devDesc =
2655 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2656 if (devDesc == 0) {
2657 return BAD_VALUE;
2658 }
2659
François Gaffie53615e22015-03-19 09:24:12 +01002660 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002661 devDesc->mAddress,
2662 patch->sinks[0].sample_rate,
2663 NULL, /*updatedSampleRate*/
2664 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002665 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002666 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002667 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002668 // FIXME for the parameter type,
2669 // and the NONE
2670 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002671 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002672 return INVALID_OPERATION;
2673 }
2674 // TODO: reconfigure output format and channels here
2675 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002676 devDesc->type(), inputDesc->mIoHandle);
2677 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002678 index = mAudioPatches.indexOfKey(*handle);
2679 if (index >= 0) {
2680 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2681 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2682 }
2683 patchDesc = mAudioPatches.valueAt(index);
2684 patchDesc->mUid = uid;
2685 ALOGV("createAudioPatch() success");
2686 } else {
2687 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2688 return INVALID_OPERATION;
2689 }
2690 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2691 // device to device connection
2692 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002693 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002694 return BAD_VALUE;
2695 }
2696 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002697 sp<DeviceDescriptor> srcDeviceDesc =
2698 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002699 if (srcDeviceDesc == 0) {
2700 return BAD_VALUE;
2701 }
Eric Laurent874c42872014-08-08 15:13:39 -07002702
Eric Laurent6a94d692014-05-20 11:18:06 -07002703 //update source and sink with our own data as the data passed in the patch may
2704 // be incomplete.
2705 struct audio_patch newPatch = *patch;
2706 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002707
Eric Laurent874c42872014-08-08 15:13:39 -07002708 for (size_t i = 0; i < patch->num_sinks; i++) {
2709 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2710 ALOGV("createAudioPatch() source device but one sink is not a device");
2711 return INVALID_OPERATION;
2712 }
2713
2714 sp<DeviceDescriptor> sinkDeviceDesc =
2715 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2716 if (sinkDeviceDesc == 0) {
2717 return BAD_VALUE;
2718 }
2719 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2720
Eric Laurent3bcf8592015-04-03 12:13:24 -07002721 // create a software bridge in PatchPanel if:
2722 // - source and sink devices are on differnt HW modules OR
2723 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002724 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002725 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002726 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002727 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002728 return INVALID_OPERATION;
2729 }
Eric Laurent874c42872014-08-08 15:13:39 -07002730 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002731 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002732 // if the sink device is reachable via an opened output stream, request to go via
2733 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002734 audio_io_handle_t output = selectOutput(outputs,
2735 AUDIO_OUTPUT_FLAG_NONE,
2736 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002737 if (output != AUDIO_IO_HANDLE_NONE) {
2738 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2739 if (outputDesc->isDuplicated()) {
2740 return INVALID_OPERATION;
2741 }
2742 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002743 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002744 newPatch.num_sources = 2;
2745 }
Eric Laurent83b88082014-06-20 18:31:16 -07002746 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 }
2748 // TODO: check from routing capabilities in config file and other conflicting patches
2749
2750 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2751 if (index >= 0) {
2752 afPatchHandle = patchDesc->mAfPatchHandle;
2753 }
2754
2755 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2756 &afPatchHandle,
2757 0);
2758 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2759 status, afPatchHandle);
2760 if (status == NO_ERROR) {
2761 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002762 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 addAudioPatch(patchDesc->mHandle, patchDesc);
2764 } else {
2765 patchDesc->mPatch = newPatch;
2766 }
2767 patchDesc->mAfPatchHandle = afPatchHandle;
2768 *handle = patchDesc->mHandle;
2769 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002770 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002771 } else {
2772 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2773 status);
2774 return INVALID_OPERATION;
2775 }
2776 } else {
2777 return BAD_VALUE;
2778 }
2779 } else {
2780 return BAD_VALUE;
2781 }
2782 return NO_ERROR;
2783}
2784
2785status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2786 uid_t uid)
2787{
2788 ALOGV("releaseAudioPatch() patch %d", handle);
2789
2790 ssize_t index = mAudioPatches.indexOfKey(handle);
2791
2792 if (index < 0) {
2793 return BAD_VALUE;
2794 }
2795 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2796 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2797 mUidCached, patchDesc->mUid, uid);
2798 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2799 return INVALID_OPERATION;
2800 }
2801
2802 struct audio_patch *patch = &patchDesc->mPatch;
2803 patchDesc->mUid = mUidCached;
2804 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002805 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002806 if (outputDesc == NULL) {
2807 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2808 return BAD_VALUE;
2809 }
2810
Eric Laurentc75307b2015-03-17 15:29:32 -07002811 setOutputDevice(outputDesc,
2812 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 true,
2814 0,
2815 NULL);
2816 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2817 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002818 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002819 if (inputDesc == NULL) {
2820 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2821 return BAD_VALUE;
2822 }
2823 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002824 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002825 true,
2826 NULL);
2827 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2829 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2830 status, patchDesc->mAfPatchHandle);
2831 removeAudioPatch(patchDesc->mHandle);
2832 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002833 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 } else {
2835 return BAD_VALUE;
2836 }
2837 } else {
2838 return BAD_VALUE;
2839 }
2840 return NO_ERROR;
2841}
2842
2843status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2844 struct audio_patch *patches,
2845 unsigned int *generation)
2846{
François Gaffie53615e22015-03-19 09:24:12 +01002847 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 return BAD_VALUE;
2849 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002850 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002851 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002852}
2853
Eric Laurente1715a42014-05-20 11:30:42 -07002854status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002855{
Eric Laurente1715a42014-05-20 11:30:42 -07002856 ALOGV("setAudioPortConfig()");
2857
2858 if (config == NULL) {
2859 return BAD_VALUE;
2860 }
2861 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2862 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002863 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2864 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002865 }
2866
Eric Laurenta121f902014-06-03 13:32:54 -07002867 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002868 if (config->type == AUDIO_PORT_TYPE_MIX) {
2869 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002870 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002871 if (outputDesc == NULL) {
2872 return BAD_VALUE;
2873 }
Eric Laurent84c70242014-06-23 08:46:27 -07002874 ALOG_ASSERT(!outputDesc->isDuplicated(),
2875 "setAudioPortConfig() called on duplicated output %d",
2876 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002877 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002878 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002879 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002880 if (inputDesc == NULL) {
2881 return BAD_VALUE;
2882 }
Eric Laurenta121f902014-06-03 13:32:54 -07002883 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002884 } else {
2885 return BAD_VALUE;
2886 }
2887 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2888 sp<DeviceDescriptor> deviceDesc;
2889 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2890 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2891 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2892 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2893 } else {
2894 return BAD_VALUE;
2895 }
2896 if (deviceDesc == NULL) {
2897 return BAD_VALUE;
2898 }
Eric Laurenta121f902014-06-03 13:32:54 -07002899 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002900 } else {
2901 return BAD_VALUE;
2902 }
2903
Eric Laurenta121f902014-06-03 13:32:54 -07002904 struct audio_port_config backupConfig;
2905 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2906 if (status == NO_ERROR) {
2907 struct audio_port_config newConfig;
2908 audioPortConfig->toAudioPortConfig(&newConfig, config);
2909 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002910 }
Eric Laurenta121f902014-06-03 13:32:54 -07002911 if (status != NO_ERROR) {
2912 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002913 }
Eric Laurente1715a42014-05-20 11:30:42 -07002914
2915 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002916}
2917
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002918void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2919{
Eric Laurentd60560a2015-04-10 11:31:20 -07002920 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002921 clearAudioPatches(uid);
2922 clearSessionRoutes(uid);
2923}
2924
Eric Laurent6a94d692014-05-20 11:18:06 -07002925void AudioPolicyManager::clearAudioPatches(uid_t uid)
2926{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002927 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002928 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2929 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002930 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002931 }
2932 }
2933}
2934
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002935void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2936 audio_io_handle_t ouptutToSkip)
2937{
2938 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2939 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2940 for (size_t j = 0; j < mOutputs.size(); j++) {
2941 if (mOutputs.keyAt(j) == ouptutToSkip) {
2942 continue;
2943 }
2944 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2945 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2946 continue;
2947 }
2948 // If the default device for this strategy is on another output mix,
2949 // invalidate all tracks in this strategy to force re connection.
2950 // Otherwise select new device on the output mix.
2951 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002952 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002953 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2954 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2955 }
2956 }
2957 } else {
2958 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2959 setOutputDevice(outputDesc, newDevice, false);
2960 }
2961 }
2962}
2963
2964void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2965{
2966 // remove output routes associated with this uid
2967 SortedVector<routing_strategy> affectedStrategies;
2968 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2969 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2970 if (route->mUid == uid) {
2971 mOutputRoutes.removeItemsAt(i);
2972 if (route->mDeviceDescriptor != 0) {
2973 affectedStrategies.add(getStrategy(route->mStreamType));
2974 }
2975 }
2976 }
2977 // reroute outputs if necessary
2978 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2979 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2980 }
2981
2982 // remove input routes associated with this uid
2983 SortedVector<audio_source_t> affectedSources;
2984 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2985 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2986 if (route->mUid == uid) {
2987 mInputRoutes.removeItemsAt(i);
2988 if (route->mDeviceDescriptor != 0) {
2989 affectedSources.add(route->mSource);
2990 }
2991 }
2992 }
2993 // reroute inputs if necessary
2994 SortedVector<audio_io_handle_t> inputsToClose;
2995 for (size_t i = 0; i < mInputs.size(); i++) {
2996 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002997 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002998 inputsToClose.add(inputDesc->mIoHandle);
2999 }
3000 }
3001 for (size_t i = 0; i < inputsToClose.size(); i++) {
3002 closeInput(inputsToClose[i]);
3003 }
3004}
3005
Eric Laurentd60560a2015-04-10 11:31:20 -07003006void AudioPolicyManager::clearAudioSources(uid_t uid)
3007{
3008 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3009 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3010 if (sourceDesc->mUid == uid) {
3011 stopAudioSource(mAudioSources.keyAt(i));
3012 }
3013 }
3014}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003015
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003016status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3017 audio_io_handle_t *ioHandle,
3018 audio_devices_t *device)
3019{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003020 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3021 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003022 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003023
François Gaffiedf372692015-03-19 10:43:27 +01003024 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003025}
3026
Eric Laurentd60560a2015-04-10 11:31:20 -07003027status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3028 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003029 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003030 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003031{
Eric Laurentd60560a2015-04-10 11:31:20 -07003032 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3033 if (source == NULL || attributes == NULL || handle == NULL) {
3034 return BAD_VALUE;
3035 }
3036
Glenn Kasten559d4392016-03-29 13:42:57 -07003037 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003038
3039 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3040 source->type != AUDIO_PORT_TYPE_DEVICE) {
3041 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3042 return INVALID_OPERATION;
3043 }
3044
3045 sp<DeviceDescriptor> srcDeviceDesc =
3046 mAvailableInputDevices.getDevice(source->ext.device.type,
3047 String8(source->ext.device.address));
3048 if (srcDeviceDesc == 0) {
3049 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3050 return BAD_VALUE;
3051 }
3052 sp<AudioSourceDescriptor> sourceDesc =
3053 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3054
3055 struct audio_patch dummyPatch;
3056 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3057 sourceDesc->mPatchDesc = patchDesc;
3058
3059 status_t status = connectAudioSource(sourceDesc);
3060 if (status == NO_ERROR) {
3061 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3062 *handle = sourceDesc->getHandle();
3063 }
3064 return status;
3065}
3066
3067status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3068{
3069 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3070
3071 // make sure we only have one patch per source.
3072 disconnectAudioSource(sourceDesc);
3073
3074 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003075 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003076 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3077
3078 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3079 sp<DeviceDescriptor> sinkDeviceDesc =
3080 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3081
3082 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3083 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3084
3085 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3086 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003087 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003088 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3089 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3090 // create patch between src device and output device
3091 // create Hwoutput and add to mHwOutputs
3092 } else {
3093 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3094 audio_io_handle_t output =
3095 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3096 if (output == AUDIO_IO_HANDLE_NONE) {
3097 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3098 return INVALID_OPERATION;
3099 }
3100 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3101 if (outputDesc->isDuplicated()) {
3102 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3103 return INVALID_OPERATION;
3104 }
3105 // create a special patch with no sink and two sources:
3106 // - the second source indicates to PatchPanel through which output mix this patch should
3107 // be connected as well as the stream type for volume control
3108 // - the sink is defined by whatever output device is currently selected for the output
3109 // though which this patch is routed.
3110 patch->num_sinks = 0;
3111 patch->num_sources = 2;
3112 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3113 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3114 patch->sources[1].ext.mix.usecase.stream = stream;
3115 status_t status = mpClientInterface->createAudioPatch(patch,
3116 &afPatchHandle,
3117 0);
3118 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3119 status, afPatchHandle);
3120 if (status != NO_ERROR) {
3121 ALOGW("%s patch panel could not connect device patch, error %d",
3122 __FUNCTION__, status);
3123 return INVALID_OPERATION;
3124 }
3125 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003126 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003127
3128 if (status != NO_ERROR) {
3129 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3130 return status;
3131 }
3132 sourceDesc->mSwOutput = outputDesc;
3133 if (delayMs != 0) {
3134 usleep(delayMs * 1000);
3135 }
3136 }
3137
3138 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3139 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3140
3141 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003142}
3143
Glenn Kasten559d4392016-03-29 13:42:57 -07003144status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003145{
Eric Laurentd60560a2015-04-10 11:31:20 -07003146 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3147 ALOGV("%s handle %d", __FUNCTION__, handle);
3148 if (sourceDesc == 0) {
3149 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3150 return BAD_VALUE;
3151 }
3152 status_t status = disconnectAudioSource(sourceDesc);
3153
3154 mAudioSources.removeItem(handle);
3155 return status;
3156}
3157
Andy Hung2ddee192015-12-18 17:34:44 -08003158status_t AudioPolicyManager::setMasterMono(bool mono)
3159{
3160 if (mMasterMono == mono) {
3161 return NO_ERROR;
3162 }
3163 mMasterMono = mono;
3164 // if enabling mono we close all offloaded devices, which will invalidate the
3165 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3166 // for recreating the new AudioTrack as non-offloaded PCM.
3167 //
3168 // If disabling mono, we leave all tracks as is: we don't know which clients
3169 // and tracks are able to be recreated as offloaded. The next "song" should
3170 // play back offloaded.
3171 if (mMasterMono) {
3172 Vector<audio_io_handle_t> offloaded;
3173 for (size_t i = 0; i < mOutputs.size(); ++i) {
3174 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3175 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3176 offloaded.push(desc->mIoHandle);
3177 }
3178 }
3179 for (size_t i = 0; i < offloaded.size(); ++i) {
3180 closeOutput(offloaded[i]);
3181 }
3182 }
3183 // update master mono for all remaining outputs
3184 for (size_t i = 0; i < mOutputs.size(); ++i) {
3185 updateMono(mOutputs.keyAt(i));
3186 }
3187 return NO_ERROR;
3188}
3189
3190status_t AudioPolicyManager::getMasterMono(bool *mono)
3191{
3192 *mono = mMasterMono;
3193 return NO_ERROR;
3194}
3195
Eric Laurentd60560a2015-04-10 11:31:20 -07003196status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3197{
3198 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3199
3200 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3201 if (patchDesc == 0) {
3202 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3203 sourceDesc->mPatchDesc->mHandle);
3204 return BAD_VALUE;
3205 }
3206 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3207
Eric Laurent28d09f02016-03-08 10:43:05 -08003208 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003209 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3210 if (swOutputDesc != 0) {
3211 stopSource(swOutputDesc, stream, false);
3212 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3213 } else {
3214 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3215 if (hwOutputDesc != 0) {
3216 // release patch between src device and output device
3217 // close Hwoutput and remove from mHwOutputs
3218 } else {
3219 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3220 }
3221 }
3222 return NO_ERROR;
3223}
3224
3225sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3226 audio_io_handle_t output, routing_strategy strategy)
3227{
3228 sp<AudioSourceDescriptor> source;
3229 for (size_t i = 0; i < mAudioSources.size(); i++) {
3230 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3231 routing_strategy sourceStrategy =
3232 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3233 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3234 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3235 source = sourceDesc;
3236 break;
3237 }
3238 }
3239 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003240}
3241
Eric Laurente552edb2014-03-10 17:42:56 -07003242// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003243// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003244// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003245uint32_t AudioPolicyManager::nextAudioPortGeneration()
3246{
3247 return android_atomic_inc(&mAudioPortGeneration);
3248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003251 :
3252#ifdef AUDIO_POLICY_TEST
3253 Thread(false),
3254#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003255 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003256 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003257 mAudioPortGeneration(1),
3258 mBeaconMuteRefCount(0),
3259 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003260 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003261 mTtsOutputAvailable(false),
3262 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003263{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003264 mUidCached = getuid();
3265 mpClientInterface = clientInterface;
3266
3267 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3268 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3269 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3270 bool speakerDrcEnabled = false;
3271
3272#ifdef USE_XML_AUDIO_POLICY_CONF
3273 mVolumeCurves = new VolumeCurvesCollection();
3274 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3275 mDefaultOutputDevice, speakerDrcEnabled,
3276 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3277 PolicySerializer serializer;
3278 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3279#else
3280 mVolumeCurves = new StreamDescriptorCollection();
3281 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3282 mDefaultOutputDevice, speakerDrcEnabled);
3283 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3284 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3285#endif
3286 ALOGE("could not load audio policy configuration file, setting defaults");
3287 config.setDefault();
3288 }
3289 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3290 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3291
3292 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003293 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3294 if (!engineInstance) {
3295 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3296 return;
3297 }
3298 // Retrieve the Policy Manager Interface
3299 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3300 if (mEngine == NULL) {
3301 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3302 return;
3303 }
3304 mEngine->setObserver(this);
3305 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003306 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003307 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3308
Eric Laurent3a4311c2014-03-17 12:00:47 -07003309 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003310 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003311 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3312 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003313 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003314 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003315 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003316 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003317 continue;
3318 }
3319 // open all output streams needed to access attached devices
3320 // except for direct output streams that are only opened when they are actually
3321 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003322 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003323 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3324 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003325 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003326
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003327 if (!outProfile->hasSupportedDevices()) {
3328 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003329 continue;
3330 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003331 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003332 mTtsOutputAvailable = true;
3333 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003334
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003335 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003336 continue;
3337 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003338 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003339 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3340 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003341 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003342 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003343 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003344 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003345 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003346 if ((profileType & outputDeviceTypes) == 0) {
3347 continue;
3348 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003349 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3350 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003351 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3352 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3353 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3354 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003355
3356 outputDesc->mDevice = profileType;
3357 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3358 config.sample_rate = outputDesc->mSamplingRate;
3359 config.channel_mask = outputDesc->mChannelMask;
3360 config.format = outputDesc->mFormat;
3361 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003362 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003363 &output,
3364 &config,
3365 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003366 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003367 &outputDesc->mLatency,
3368 outputDesc->mFlags);
3369
3370 if (status != NO_ERROR) {
3371 ALOGW("Cannot open output stream for device %08x on hw module %s",
3372 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003373 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003374 } else {
3375 outputDesc->mSamplingRate = config.sample_rate;
3376 outputDesc->mChannelMask = config.channel_mask;
3377 outputDesc->mFormat = config.format;
3378
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003379 for (size_t k = 0; k < supportedDevices.size(); k++) {
3380 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003381 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003382 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3383 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003384 }
3385 }
3386 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003387 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003388 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003389 }
3390 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003391 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003392 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003393 true,
3394 0,
3395 NULL,
3396 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003397 }
Eric Laurente552edb2014-03-10 17:42:56 -07003398 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003399 // open input streams needed to access attached devices to validate
3400 // mAvailableInputDevices list
3401 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3402 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003403 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003404
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003405 if (!inProfile->hasSupportedDevices()) {
3406 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003407 continue;
3408 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003409 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003410 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003411 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3412
Eric Laurentd78f1532014-09-16 16:38:20 -07003413 if ((profileType & inputDeviceTypes) == 0) {
3414 continue;
3415 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003416 sp<AudioInputDescriptor> inputDesc =
3417 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003418
Eric Laurentd78f1532014-09-16 16:38:20 -07003419 inputDesc->mDevice = profileType;
3420
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003421 // find the address
3422 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3423 // the inputs vector must be of size 1, but we don't want to crash here
3424 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3425 : String8("");
3426 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3427 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3428
Eric Laurentd78f1532014-09-16 16:38:20 -07003429 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3430 config.sample_rate = inputDesc->mSamplingRate;
3431 config.channel_mask = inputDesc->mChannelMask;
3432 config.format = inputDesc->mFormat;
3433 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003434 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003435 &input,
3436 &config,
3437 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003438 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003439 AUDIO_SOURCE_MIC,
3440 AUDIO_INPUT_FLAG_NONE);
3441
3442 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003443 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3444 for (size_t k = 0; k < supportedDevices.size(); k++) {
3445 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003446 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003447 if (index >= 0) {
3448 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3449 if (!devDesc->isAttached()) {
3450 devDesc->attach(mHwModules[i]);
3451 devDesc->importAudioPort(inProfile);
3452 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003453 }
3454 }
3455 mpClientInterface->closeInput(input);
3456 } else {
3457 ALOGW("Cannot open input stream for device %08x on hw module %s",
3458 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003459 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003460 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003461 }
3462 }
3463 // make sure all attached devices have been allocated a unique ID
3464 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003465 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003466 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003467 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3468 continue;
3469 }
François Gaffie2110e042015-03-24 08:41:51 +01003470 // The device is now validated and can be appended to the available devices of the engine
3471 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3472 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003473 i++;
3474 }
3475 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003476 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003477 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003478 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3479 continue;
3480 }
François Gaffie2110e042015-03-24 08:41:51 +01003481 // The device is now validated and can be appended to the available devices of the engine
3482 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3483 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003484 i++;
3485 }
3486 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003487 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003488 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003489 }
Eric Laurente552edb2014-03-10 17:42:56 -07003490
3491 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3492
3493 updateDevicesAndOutputs();
3494
3495#ifdef AUDIO_POLICY_TEST
3496 if (mPrimaryOutput != 0) {
3497 AudioParameter outputCmd = AudioParameter();
3498 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003499 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003500
3501 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3502 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003503 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3504 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003505 mTestLatencyMs = 0;
3506 mCurOutput = 0;
3507 mDirectOutput = false;
3508 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3509 mTestOutputs[i] = 0;
3510 }
3511
3512 const size_t SIZE = 256;
3513 char buffer[SIZE];
3514 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3515 run(buffer, ANDROID_PRIORITY_AUDIO);
3516 }
3517#endif //AUDIO_POLICY_TEST
3518}
3519
Eric Laurente0720872014-03-11 09:30:41 -07003520AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003521{
3522#ifdef AUDIO_POLICY_TEST
3523 exit();
3524#endif //AUDIO_POLICY_TEST
3525 for (size_t i = 0; i < mOutputs.size(); i++) {
3526 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003527 }
3528 for (size_t i = 0; i < mInputs.size(); i++) {
3529 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003530 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003531 mAvailableOutputDevices.clear();
3532 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003533 mOutputs.clear();
3534 mInputs.clear();
3535 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003536}
3537
Eric Laurente0720872014-03-11 09:30:41 -07003538status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003539{
Eric Laurent87ffa392015-05-22 10:32:38 -07003540 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003541}
3542
3543#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003544bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003545{
3546 ALOGV("entering threadLoop()");
3547 while (!exitPending())
3548 {
3549 String8 command;
3550 int valueInt;
3551 String8 value;
3552
3553 Mutex::Autolock _l(mLock);
3554 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3555
3556 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3557 AudioParameter param = AudioParameter(command);
3558
3559 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3560 valueInt != 0) {
3561 ALOGV("Test command %s received", command.string());
3562 String8 target;
3563 if (param.get(String8("target"), target) != NO_ERROR) {
3564 target = "Manager";
3565 }
3566 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3567 param.remove(String8("test_cmd_policy_output"));
3568 mCurOutput = valueInt;
3569 }
3570 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3571 param.remove(String8("test_cmd_policy_direct"));
3572 if (value == "false") {
3573 mDirectOutput = false;
3574 } else if (value == "true") {
3575 mDirectOutput = true;
3576 }
3577 }
3578 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3579 param.remove(String8("test_cmd_policy_input"));
3580 mTestInput = valueInt;
3581 }
3582
3583 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3584 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003585 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003586 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003587 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003588 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003589 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003590 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003591 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003592 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003593 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003594 if (target == "Manager") {
3595 mTestFormat = format;
3596 } else if (mTestOutputs[mCurOutput] != 0) {
3597 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003598 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003599 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3600 }
3601 }
3602 }
3603 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3604 param.remove(String8("test_cmd_policy_channels"));
3605 int channels = 0;
3606
3607 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003608 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003609 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003610 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003611 }
3612 if (channels != 0) {
3613 if (target == "Manager") {
3614 mTestChannels = channels;
3615 } else if (mTestOutputs[mCurOutput] != 0) {
3616 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003617 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003618 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3619 }
3620 }
3621 }
3622 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3623 param.remove(String8("test_cmd_policy_sampleRate"));
3624 if (valueInt >= 0 && valueInt <= 96000) {
3625 int samplingRate = valueInt;
3626 if (target == "Manager") {
3627 mTestSamplingRate = samplingRate;
3628 } else if (mTestOutputs[mCurOutput] != 0) {
3629 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003630 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003631 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3632 }
3633 }
3634 }
3635
3636 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3637 param.remove(String8("test_cmd_policy_reopen"));
3638
Eric Laurentc75307b2015-03-17 15:29:32 -07003639 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003640
Eric Laurentc75307b2015-03-17 15:29:32 -07003641 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003642
Eric Laurentc75307b2015-03-17 15:29:32 -07003643 removeOutput(mPrimaryOutput->mIoHandle);
3644 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3645 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003646 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003647 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3648 config.sample_rate = outputDesc->mSamplingRate;
3649 config.channel_mask = outputDesc->mChannelMask;
3650 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003651 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003652 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003653 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003654 &config,
3655 &outputDesc->mDevice,
3656 String8(""),
3657 &outputDesc->mLatency,
3658 outputDesc->mFlags);
3659 if (status != NO_ERROR) {
3660 ALOGE("Failed to reopen hardware output stream, "
3661 "samplingRate: %d, format %d, channels %d",
3662 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003663 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003664 outputDesc->mSamplingRate = config.sample_rate;
3665 outputDesc->mChannelMask = config.channel_mask;
3666 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003667 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003668 AudioParameter outputCmd = AudioParameter();
3669 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003670 mpClientInterface->setParameters(handle, outputCmd.toString());
3671 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003672 }
3673 }
3674
3675
3676 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3677 }
3678 }
3679 return false;
3680}
3681
Eric Laurente0720872014-03-11 09:30:41 -07003682void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003683{
3684 {
3685 AutoMutex _l(mLock);
3686 requestExit();
3687 mWaitWorkCV.signal();
3688 }
3689 requestExitAndWait();
3690}
3691
Eric Laurente0720872014-03-11 09:30:41 -07003692int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003693{
3694 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3695 if (output == mTestOutputs[i]) return i;
3696 }
3697 return 0;
3698}
3699#endif //AUDIO_POLICY_TEST
3700
3701// ---
3702
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003703void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003704{
François Gaffie98cc1912015-03-18 17:52:40 +01003705 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003706 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003707 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003708 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003709}
3710
François Gaffie53615e22015-03-19 09:24:12 +01003711void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3712{
3713 mOutputs.removeItem(output);
3714}
3715
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003716void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003717{
François Gaffie98cc1912015-03-18 17:52:40 +01003718 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003719 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003721}
Eric Laurente552edb2014-03-10 17:42:56 -07003722
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003723void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003724 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003725 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003726 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003727 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003728 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003729 if (devDesc != 0) {
3730 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3731 desc->mIoHandle, address.string());
3732 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003733 }
3734}
3735
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003736status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003737 audio_policy_dev_state_t state,
3738 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003739 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003740{
François Gaffie53615e22015-03-19 09:24:12 +01003741 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003742 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003743
3744 if (audio_device_is_digital(device)) {
3745 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003746 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003747 }
Eric Laurente552edb2014-03-10 17:42:56 -07003748
Eric Laurent3b73df72014-03-11 09:06:29 -07003749 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003750 // first list already open outputs that can be routed to this device
3751 for (size_t i = 0; i < mOutputs.size(); i++) {
3752 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003753 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003754 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003755 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3756 outputs.add(mOutputs.keyAt(i));
3757 } else {
3758 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003759 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003760 }
Eric Laurente552edb2014-03-10 17:42:56 -07003761 }
3762 }
3763 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003764 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003765 for (size_t i = 0; i < mHwModules.size(); i++)
3766 {
3767 if (mHwModules[i]->mHandle == 0) {
3768 continue;
3769 }
3770 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3771 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003772 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003773 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003774 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003775 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003776 profiles.add(profile);
3777 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3778 }
Eric Laurente552edb2014-03-10 17:42:56 -07003779 }
3780 }
3781 }
3782
Eric Laurent7b279bb2015-12-14 10:18:23 -08003783 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003784
Eric Laurente552edb2014-03-10 17:42:56 -07003785 if (profiles.isEmpty() && outputs.isEmpty()) {
3786 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3787 return BAD_VALUE;
3788 }
3789
3790 // open outputs for matching profiles if needed. Direct outputs are also opened to
3791 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3792 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003793 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003794
3795 // nothing to do if one output is already opened for this profile
3796 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003797 for (j = 0; j < outputs.size(); j++) {
3798 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003799 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003800 // matching profile: save the sample rates, format and channel masks supported
3801 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003802 if (audio_device_is_digital(device)) {
3803 devDesc->importAudioPort(profile);
3804 }
Eric Laurente552edb2014-03-10 17:42:56 -07003805 break;
3806 }
3807 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003808 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003809 continue;
3810 }
3811
Eric Laurent83b88082014-06-20 18:31:16 -07003812 ALOGV("opening output for device %08x with params %s profile %p",
3813 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003814 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003815 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003816 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3817 config.sample_rate = desc->mSamplingRate;
3818 config.channel_mask = desc->mChannelMask;
3819 config.format = desc->mFormat;
3820 config.offload_info.sample_rate = desc->mSamplingRate;
3821 config.offload_info.channel_mask = desc->mChannelMask;
3822 config.offload_info.format = desc->mFormat;
3823 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003824 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003825 &output,
3826 &config,
3827 &desc->mDevice,
3828 address,
3829 &desc->mLatency,
3830 desc->mFlags);
3831 if (status == NO_ERROR) {
3832 desc->mSamplingRate = config.sample_rate;
3833 desc->mChannelMask = config.channel_mask;
3834 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003835
Eric Laurentd4692962014-05-05 18:13:44 -07003836 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003837 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003838 char *param = audio_device_address_to_parameter(device, address);
3839 mpClientInterface->setParameters(output, String8(param));
3840 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003841 }
Phil Burk00eeb322016-03-31 12:41:00 -07003842 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003843 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003844 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003845 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003846 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003847 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003848 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003849 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003850 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003851 config.offload_info.sample_rate = config.sample_rate;
3852 config.offload_info.channel_mask = config.channel_mask;
3853 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003854 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003855 &output,
3856 &config,
3857 &desc->mDevice,
3858 address,
3859 &desc->mLatency,
3860 desc->mFlags);
3861 if (status == NO_ERROR) {
3862 desc->mSamplingRate = config.sample_rate;
3863 desc->mChannelMask = config.channel_mask;
3864 desc->mFormat = config.format;
3865 } else {
3866 output = AUDIO_IO_HANDLE_NONE;
3867 }
Eric Laurentd4692962014-05-05 18:13:44 -07003868 }
3869
Eric Laurentcf2c0212014-07-25 16:20:43 -07003870 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003871 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003872 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003873 sp<AudioPolicyMix> policyMix;
3874 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003875 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3876 address.string());
3877 }
François Gaffie036e1e92015-03-19 10:16:24 +01003878 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003879 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003880
Eric Laurent87ffa392015-05-22 10:32:38 -07003881 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3882 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003883 // no duplicated output for direct outputs and
3884 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003885 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003886
Eric Laurentd4692962014-05-05 18:13:44 -07003887 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003888 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003889
Eric Laurentd4692962014-05-05 18:13:44 -07003890 //TODO: configure audio effect output stage here
3891
3892 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003893 duplicatedOutput =
3894 mpClientInterface->openDuplicateOutput(output,
3895 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003896 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003897 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003898 sp<SwAudioOutputDescriptor> dupOutputDesc =
3899 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3900 dupOutputDesc->mOutput1 = mPrimaryOutput;
3901 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003902 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3903 dupOutputDesc->mFormat = desc->mFormat;
3904 dupOutputDesc->mChannelMask = desc->mChannelMask;
3905 dupOutputDesc->mLatency = desc->mLatency;
3906 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003907 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003908 } else {
3909 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003910 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003911 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003912 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003913 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003914 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003915 }
Eric Laurente552edb2014-03-10 17:42:56 -07003916 }
3917 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003918 } else {
3919 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003920 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003921 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003922 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003923 profiles.removeAt(profile_index);
3924 profile_index--;
3925 } else {
3926 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003927 // Load digital format info only for digital devices
3928 if (audio_device_is_digital(device)) {
3929 devDesc->importAudioPort(profile);
3930 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003931
François Gaffie53615e22015-03-19 09:24:12 +01003932 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003933 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3934 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003935 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003936 NULL/*patch handle*/, address.string());
3937 }
Eric Laurente552edb2014-03-10 17:42:56 -07003938 ALOGV("checkOutputsForDevice(): adding output %d", output);
3939 }
3940 }
3941
3942 if (profiles.isEmpty()) {
3943 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3944 return BAD_VALUE;
3945 }
Eric Laurentd4692962014-05-05 18:13:44 -07003946 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003947 // check if one opened output is not needed any more after disconnecting one device
3948 for (size_t i = 0; i < mOutputs.size(); i++) {
3949 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003950 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003951 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003952 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003953 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003954 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003955 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003956 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3957 mOutputs.keyAt(i));
3958 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003959 }
Eric Laurente552edb2014-03-10 17:42:56 -07003960 }
3961 }
Eric Laurentd4692962014-05-05 18:13:44 -07003962 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003963 for (size_t i = 0; i < mHwModules.size(); i++)
3964 {
3965 if (mHwModules[i]->mHandle == 0) {
3966 continue;
3967 }
3968 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3969 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003970 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003971 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003972 ALOGV("checkOutputsForDevice(): "
3973 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003974 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003975 }
3976 }
3977 }
3978 }
3979 return NO_ERROR;
3980}
3981
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003982status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003983 audio_policy_dev_state_t state,
3984 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003985 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07003986{
Paul McLean9080a4c2015-06-18 08:24:02 -07003987 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003988 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003989
3990 if (audio_device_is_digital(device)) {
3991 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003992 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003993 }
3994
Eric Laurentd4692962014-05-05 18:13:44 -07003995 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3996 // first list already open inputs that can be routed to this device
3997 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3998 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003999 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004000 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4001 inputs.add(mInputs.keyAt(input_index));
4002 }
4003 }
4004
4005 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004006 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004007 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4008 {
4009 if (mHwModules[module_idx]->mHandle == 0) {
4010 continue;
4011 }
4012 for (size_t profile_index = 0;
4013 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4014 profile_index++)
4015 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004016 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4017
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004019 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004020 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004021 profiles.add(profile);
4022 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4023 profile_index, module_idx);
4024 }
Eric Laurentd4692962014-05-05 18:13:44 -07004025 }
4026 }
4027 }
4028
4029 if (profiles.isEmpty() && inputs.isEmpty()) {
4030 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4031 return BAD_VALUE;
4032 }
4033
4034 // open inputs for matching profiles if needed. Direct inputs are also opened to
4035 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4036 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4037
Eric Laurent1c333e22014-05-20 10:48:17 -07004038 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004039 // nothing to do if one input is already opened for this profile
4040 size_t input_index;
4041 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4042 desc = mInputs.valueAt(input_index);
4043 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004044 if (audio_device_is_digital(device)) {
4045 devDesc->importAudioPort(profile);
4046 }
Eric Laurentd4692962014-05-05 18:13:44 -07004047 break;
4048 }
4049 }
4050 if (input_index != mInputs.size()) {
4051 continue;
4052 }
4053
4054 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4055 desc = new AudioInputDescriptor(profile);
4056 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004057 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4058 config.sample_rate = desc->mSamplingRate;
4059 config.channel_mask = desc->mChannelMask;
4060 config.format = desc->mFormat;
4061 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004062 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004063 &input,
4064 &config,
4065 &desc->mDevice,
4066 address,
4067 AUDIO_SOURCE_MIC,
4068 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004069
Eric Laurentcf2c0212014-07-25 16:20:43 -07004070 if (status == NO_ERROR) {
4071 desc->mSamplingRate = config.sample_rate;
4072 desc->mChannelMask = config.channel_mask;
4073 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004074
Eric Laurentd4692962014-05-05 18:13:44 -07004075 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004076 char *param = audio_device_address_to_parameter(device, address);
4077 mpClientInterface->setParameters(input, String8(param));
4078 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004079 }
Phil Burk00eeb322016-03-31 12:41:00 -07004080 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004081 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004082 ALOGW("checkInputsForDevice() direct input missing param");
4083 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004084 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004085 }
4086
4087 if (input != 0) {
4088 addInput(input, desc);
4089 }
4090 } // endif input != 0
4091
Eric Laurentcf2c0212014-07-25 16:20:43 -07004092 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004093 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004094 profiles.removeAt(profile_index);
4095 profile_index--;
4096 } else {
4097 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004098 if (audio_device_is_digital(device)) {
4099 devDesc->importAudioPort(profile);
4100 }
Eric Laurentd4692962014-05-05 18:13:44 -07004101 ALOGV("checkInputsForDevice(): adding input %d", input);
4102 }
4103 } // end scan profiles
4104
4105 if (profiles.isEmpty()) {
4106 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4107 return BAD_VALUE;
4108 }
4109 } else {
4110 // Disconnect
4111 // check if one opened input is not needed any more after disconnecting one device
4112 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4113 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004114 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004115 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4116 mInputs.keyAt(input_index));
4117 inputs.add(mInputs.keyAt(input_index));
4118 }
4119 }
4120 // Clear any profiles associated with the disconnected device.
4121 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4122 if (mHwModules[module_index]->mHandle == 0) {
4123 continue;
4124 }
4125 for (size_t profile_index = 0;
4126 profile_index < mHwModules[module_index]->mInputProfiles.size();
4127 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004128 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004129 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004130 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004131 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004132 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004133 }
4134 }
4135 }
4136 } // end disconnect
4137
4138 return NO_ERROR;
4139}
4140
4141
Eric Laurente0720872014-03-11 09:30:41 -07004142void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004143{
4144 ALOGV("closeOutput(%d)", output);
4145
Eric Laurentc75307b2015-03-17 15:29:32 -07004146 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004147 if (outputDesc == NULL) {
4148 ALOGW("closeOutput() unknown output %d", output);
4149 return;
4150 }
François Gaffie036e1e92015-03-19 10:16:24 +01004151 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004152
Eric Laurente552edb2014-03-10 17:42:56 -07004153 // look for duplicated outputs connected to the output being removed.
4154 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004155 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004156 if (dupOutputDesc->isDuplicated() &&
4157 (dupOutputDesc->mOutput1 == outputDesc ||
4158 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004159 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004160 if (dupOutputDesc->mOutput1 == outputDesc) {
4161 outputDesc2 = dupOutputDesc->mOutput2;
4162 } else {
4163 outputDesc2 = dupOutputDesc->mOutput1;
4164 }
4165 // As all active tracks on duplicated output will be deleted,
4166 // and as they were also referenced on the other output, the reference
4167 // count for their stream type must be adjusted accordingly on
4168 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004169 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004170 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004171 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004172 }
4173 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4174 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4175
4176 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004177 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
4179 }
4180
Eric Laurent05b90f82014-08-27 15:32:29 -07004181 nextAudioPortGeneration();
4182
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004183 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004184 if (index >= 0) {
4185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004186 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004187 mAudioPatches.removeItemsAt(index);
4188 mpClientInterface->onAudioPatchListUpdate();
4189 }
4190
Eric Laurente552edb2014-03-10 17:42:56 -07004191 AudioParameter param;
4192 param.add(String8("closing"), String8("true"));
4193 mpClientInterface->setParameters(output, param.toString());
4194
4195 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004196 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004197 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004198}
4199
4200void AudioPolicyManager::closeInput(audio_io_handle_t input)
4201{
4202 ALOGV("closeInput(%d)", input);
4203
4204 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4205 if (inputDesc == NULL) {
4206 ALOGW("closeInput() unknown input %d", input);
4207 return;
4208 }
4209
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004211
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004212 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004213 if (index >= 0) {
4214 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004215 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004216 mAudioPatches.removeItemsAt(index);
4217 mpClientInterface->onAudioPatchListUpdate();
4218 }
4219
4220 mpClientInterface->closeInput(input);
4221 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004222}
4223
Eric Laurentc75307b2015-03-17 15:29:32 -07004224SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4225 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004226 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004227{
4228 SortedVector<audio_io_handle_t> outputs;
4229
4230 ALOGVV("getOutputsForDevice() device %04x", device);
4231 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004232 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004233 i, openOutputs.valueAt(i)->isDuplicated(),
4234 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004235 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4236 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4237 outputs.add(openOutputs.keyAt(i));
4238 }
4239 }
4240 return outputs;
4241}
4242
Eric Laurente0720872014-03-11 09:30:41 -07004243bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004244 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004245{
4246 if (outputs1.size() != outputs2.size()) {
4247 return false;
4248 }
4249 for (size_t i = 0; i < outputs1.size(); i++) {
4250 if (outputs1[i] != outputs2[i]) {
4251 return false;
4252 }
4253 }
4254 return true;
4255}
4256
Eric Laurente0720872014-03-11 09:30:41 -07004257void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004258{
4259 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4260 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4261 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4262 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4263
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004264 // also take into account external policy-related changes: add all outputs which are
4265 // associated with policies in the "before" and "after" output vectors
4266 ALOGVV("checkOutputForStrategy(): policy related outputs");
4267 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004268 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004269 if (desc != 0 && desc->mPolicyMix != NULL) {
4270 srcOutputs.add(desc->mIoHandle);
4271 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4272 }
4273 }
4274 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004275 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004276 if (desc != 0 && desc->mPolicyMix != NULL) {
4277 dstOutputs.add(desc->mIoHandle);
4278 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4279 }
4280 }
4281
Eric Laurente552edb2014-03-10 17:42:56 -07004282 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4283 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4284 strategy, srcOutputs[0], dstOutputs[0]);
4285 // mute strategy while moving tracks from one output to another
4286 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004288 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004289 setStrategyMute(strategy, true, desc);
4290 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004291 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004292 sp<AudioSourceDescriptor> source =
4293 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4294 if (source != 0){
4295 connectAudioSource(source);
4296 }
Eric Laurente552edb2014-03-10 17:42:56 -07004297 }
4298
4299 // Move effects associated to this strategy from previous output to new output
4300 if (strategy == STRATEGY_MEDIA) {
4301 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4302 SortedVector<audio_io_handle_t> moved;
4303 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004304 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4305 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4306 effectDesc->mIo != fxOutput) {
4307 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004308 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4309 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004310 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004311 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004312 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004313 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004314 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316 }
4317 }
4318 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004319 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004320 if (getStrategy((audio_stream_type_t)i) == strategy) {
4321 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004322 }
4323 }
4324 }
4325}
4326
Eric Laurente0720872014-03-11 09:30:41 -07004327void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004328{
François Gaffie2110e042015-03-24 08:41:51 +01004329 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004330 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004331 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004332 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004333 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004334 checkOutputForStrategy(STRATEGY_SONIFICATION);
4335 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004336 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004337 checkOutputForStrategy(STRATEGY_MEDIA);
4338 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004339 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004340}
4341
Eric Laurente0720872014-03-11 09:30:41 -07004342void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004343{
François Gaffie53615e22015-03-19 09:24:12 +01004344 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004345 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004346 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004347 return;
4348 }
4349
Eric Laurent3a4311c2014-03-17 12:00:47 -07004350 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004351 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4352 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4353 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004354
4355 // if suspended, restore A2DP output if:
4356 // ((SCO device is NOT connected) ||
4357 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4358 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004359 //
Eric Laurentf732e072016-08-03 19:30:28 -07004360 // if not suspended, suspend A2DP output if:
4361 // (SCO device is connected) &&
4362 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4363 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004364 //
4365 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004366 if (!isScoConnected ||
4367 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4368 AUDIO_POLICY_FORCE_BT_SCO) &&
4369 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4370 AUDIO_POLICY_FORCE_BT_SCO) &&
4371 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004372 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004373
4374 mpClientInterface->restoreOutput(a2dpOutput);
4375 mA2dpSuspended = false;
4376 }
4377 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004378 if (isScoConnected &&
4379 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4380 AUDIO_POLICY_FORCE_BT_SCO) ||
4381 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4382 AUDIO_POLICY_FORCE_BT_SCO) ||
4383 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004384 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004385
4386 mpClientInterface->suspendOutput(a2dpOutput);
4387 mA2dpSuspended = true;
4388 }
4389 }
4390}
4391
Eric Laurentc75307b2015-03-17 15:29:32 -07004392audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4393 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004394{
4395 audio_devices_t device = AUDIO_DEVICE_NONE;
4396
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004397 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004398 if (index >= 0) {
4399 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4400 if (patchDesc->mUid != mUidCached) {
4401 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004402 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 return outputDesc->device();
4404 }
4405 }
4406
Eric Laurente552edb2014-03-10 17:42:56 -07004407 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004408 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004409 // use device for strategy enforced audible
4410 // 2: we are in call or the strategy phone is active on the output:
4411 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004412 // 3: the strategy for enforced audible is active but not enforced on the output:
4413 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004414 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004415 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004416 // 5: the strategy accessibility is active on the output:
4417 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004418 // 6: the strategy "respectful" sonification is active on the output:
4419 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004420 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004421 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004422 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004423 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004424 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004425 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004426 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004427 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004428 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4429 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004430 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004431 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004432 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004433 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004434 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004435 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004436 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4437 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004438 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004439 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004440 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004441 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004442 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004443 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004444 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004445 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004446 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004447 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004448 }
4449
Eric Laurent1c333e22014-05-20 10:48:17 -07004450 ALOGV("getNewOutputDevice() selected device %x", device);
4451 return device;
4452}
4453
Eric Laurentfb66dd92016-01-28 18:32:03 -08004454audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004455{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004456 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004457
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004458 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004459 if (index >= 0) {
4460 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4461 if (patchDesc->mUid != mUidCached) {
4462 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004463 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 return inputDesc->mDevice;
4465 }
4466 }
4467
Eric Laurentfb66dd92016-01-28 18:32:03 -08004468 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4469 if (isInCall()) {
4470 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4471 } else if (source != AUDIO_SOURCE_DEFAULT) {
4472 device = getDeviceAndMixForInputSource(source);
4473 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004474
Eric Laurente552edb2014-03-10 17:42:56 -07004475 return device;
4476}
4477
Eric Laurent794fde22016-03-11 09:50:45 -08004478bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4479 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004480 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004481}
4482
Eric Laurente0720872014-03-11 09:30:41 -07004483uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004484 return (uint32_t)getStrategy(stream);
4485}
4486
Eric Laurente0720872014-03-11 09:30:41 -07004487audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004488 // By checking the range of stream before calling getStrategy, we avoid
4489 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4490 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004491 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 return AUDIO_DEVICE_NONE;
4493 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004494 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004495 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4496 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004497 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 }
Eric Laurent794fde22016-03-11 09:50:45 -08004499 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004500 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004501 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004502 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4503 for (size_t i = 0; i < outputs.size(); i++) {
4504 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004505 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004506 curDevices |= outputDesc->device();
4507 }
4508 }
4509 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004510 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004511
4512 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4513 and doesn't really need to.*/
4514 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4515 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4516 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4517 }
Eric Laurente552edb2014-03-10 17:42:56 -07004518 return devices;
4519}
4520
François Gaffie2110e042015-03-24 08:41:51 +01004521routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4522{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004523 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004524 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004525}
4526
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004527uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4528 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004529 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4530 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4531 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004532 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4533 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4534 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004535 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004536 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004537}
4538
Eric Laurente0720872014-03-11 09:30:41 -07004539void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004540 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004541 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004542 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4543 updateDevicesAndOutputs();
4544 break;
4545 default:
4546 break;
4547 }
4548}
4549
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004550uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004551
4552 // skip beacon mute management if a dedicated TTS output is available
4553 if (mTtsOutputAvailable) {
4554 return 0;
4555 }
4556
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004557 switch(event) {
4558 case STARTING_OUTPUT:
4559 mBeaconMuteRefCount++;
4560 break;
4561 case STOPPING_OUTPUT:
4562 if (mBeaconMuteRefCount > 0) {
4563 mBeaconMuteRefCount--;
4564 }
4565 break;
4566 case STARTING_BEACON:
4567 mBeaconPlayingRefCount++;
4568 break;
4569 case STOPPING_BEACON:
4570 if (mBeaconPlayingRefCount > 0) {
4571 mBeaconPlayingRefCount--;
4572 }
4573 break;
4574 }
4575
4576 if (mBeaconMuteRefCount > 0) {
4577 // any playback causes beacon to be muted
4578 return setBeaconMute(true);
4579 } else {
4580 // no other playback: unmute when beacon starts playing, mute when it stops
4581 return setBeaconMute(mBeaconPlayingRefCount == 0);
4582 }
4583}
4584
4585uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4586 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4587 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4588 // keep track of muted state to avoid repeating mute/unmute operations
4589 if (mBeaconMuted != mute) {
4590 // mute/unmute AUDIO_STREAM_TTS on all outputs
4591 ALOGV("\t muting %d", mute);
4592 uint32_t maxLatency = 0;
4593 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004594 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004595 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004596 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004597 0 /*delay*/, AUDIO_DEVICE_NONE);
4598 const uint32_t latency = desc->latency() * 2;
4599 if (latency > maxLatency) {
4600 maxLatency = latency;
4601 }
4602 }
4603 mBeaconMuted = mute;
4604 return maxLatency;
4605 }
4606 return 0;
4607}
4608
Eric Laurente0720872014-03-11 09:30:41 -07004609audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004610 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004611{
Paul McLeanaa981192015-03-21 09:55:15 -07004612 // Routing
4613 // see if we have an explicit route
4614 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4615 // (getStrategy(stream)).
4616 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4617 // and activity count is non-zero
4618 // the device = the device from the descriptor in the RouteMap, and exit.
4619 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4620 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004621 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4622 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004623 return route->mDeviceDescriptor->type();
4624 }
4625 }
4626
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if (fromCache) {
4628 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4629 strategy, mDeviceForStrategy[strategy]);
4630 return mDeviceForStrategy[strategy];
4631 }
François Gaffie2110e042015-03-24 08:41:51 +01004632 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004633}
4634
Eric Laurente0720872014-03-11 09:30:41 -07004635void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
4637 for (int i = 0; i < NUM_STRATEGIES; i++) {
4638 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4639 }
4640 mPreviousOutputs = mOutputs;
4641}
4642
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004643uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004644 audio_devices_t prevDevice,
4645 uint32_t delayMs)
4646{
4647 // mute/unmute strategies using an incompatible device combination
4648 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4649 // if unmuting, unmute only after the specified delay
4650 if (outputDesc->isDuplicated()) {
4651 return 0;
4652 }
4653
4654 uint32_t muteWaitMs = 0;
4655 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004656 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004657
4658 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4659 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004661 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4662 bool doMute = false;
4663
4664 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4665 doMute = true;
4666 outputDesc->mStrategyMutedByDevice[i] = true;
4667 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4668 doMute = true;
4669 outputDesc->mStrategyMutedByDevice[i] = false;
4670 }
Eric Laurent99401132014-05-07 19:48:15 -07004671 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004672 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004673 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 // skip output if it does not share any device with current output
4675 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4676 == AUDIO_DEVICE_NONE) {
4677 continue;
4678 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004679 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004680 mute ? "muting" : "unmuting", i, curDevice);
4681 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004682 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004683 if (mute) {
4684 // FIXME: should not need to double latency if volume could be applied
4685 // immediately by the audioflinger mixer. We must account for the delay
4686 // between now and the next time the audioflinger thread for this output
4687 // will process a buffer (which corresponds to one buffer size,
4688 // usually 1/2 or 1/4 of the latency).
4689 if (muteWaitMs < desc->latency() * 2) {
4690 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004691 }
4692 }
4693 }
4694 }
4695 }
4696 }
4697
Eric Laurent99401132014-05-07 19:48:15 -07004698 // temporary mute output if device selection changes to avoid volume bursts due to
4699 // different per device volumes
4700 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004701 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4702 // temporary mute duration is conservatively set to 4 times the reported latency
4703 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4704 if (muteWaitMs < tempMuteWaitMs) {
4705 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004706 }
Eric Laurentdc462862016-07-19 12:29:53 -07004707
Eric Laurent99401132014-05-07 19:48:15 -07004708 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004709 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004710 // make sure that we do not start the temporary mute period too early in case of
4711 // delayed device change
4712 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004713 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004714 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004715 }
4716 }
4717 }
4718
Eric Laurente552edb2014-03-10 17:42:56 -07004719 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4720 if (muteWaitMs > delayMs) {
4721 muteWaitMs -= delayMs;
4722 usleep(muteWaitMs * 1000);
4723 return muteWaitMs;
4724 }
4725 return 0;
4726}
4727
Eric Laurentc75307b2015-03-17 15:29:32 -07004728uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004729 audio_devices_t device,
4730 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004732 audio_patch_handle_t *patchHandle,
4733 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004734{
Eric Laurentc75307b2015-03-17 15:29:32 -07004735 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004736 AudioParameter param;
4737 uint32_t muteWaitMs;
4738
4739 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004740 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4741 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004742 return muteWaitMs;
4743 }
4744 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4745 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004746 if ((device != AUDIO_DEVICE_NONE) &&
4747 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004748 return 0;
4749 }
4750
4751 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004752 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004753
4754 audio_devices_t prevDevice = outputDesc->mDevice;
4755
Paul McLeanaa981192015-03-21 09:55:15 -07004756 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004757
4758 if (device != AUDIO_DEVICE_NONE) {
4759 outputDesc->mDevice = device;
4760 }
4761 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4762
4763 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004764 // the requested device is AUDIO_DEVICE_NONE
4765 // OR the requested device is the same as current device
4766 // AND force is not specified
4767 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004768 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004769 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4770 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004771 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004772 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004773 return muteWaitMs;
4774 }
4775
4776 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004777
Eric Laurente552edb2014-03-10 17:42:56 -07004778 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004779 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004780 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004781 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004782 DeviceVector deviceList;
4783 if ((address == NULL) || (strlen(address) == 0)) {
4784 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4785 } else {
4786 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4787 }
4788
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 if (!deviceList.isEmpty()) {
4790 struct audio_patch patch;
4791 outputDesc->toAudioPortConfig(&patch.sources[0]);
4792 patch.num_sources = 1;
4793 patch.num_sinks = 0;
4794 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4795 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004796 patch.num_sinks++;
4797 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 ssize_t index;
4799 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4800 index = mAudioPatches.indexOfKey(*patchHandle);
4801 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004802 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 }
4804 sp< AudioPatch> patchDesc;
4805 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4806 if (index >= 0) {
4807 patchDesc = mAudioPatches.valueAt(index);
4808 afPatchHandle = patchDesc->mAfPatchHandle;
4809 }
4810
Eric Laurent1c333e22014-05-20 10:48:17 -07004811 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 &afPatchHandle,
4813 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004814 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4815 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004817 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004819 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 addAudioPatch(patchDesc->mHandle, patchDesc);
4821 } else {
4822 patchDesc->mPatch = patch;
4823 }
4824 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004825 if (patchHandle) {
4826 *patchHandle = patchDesc->mHandle;
4827 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004828 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004830 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004831 }
4832 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004833
4834 // inform all input as well
4835 for (size_t i = 0; i < mInputs.size(); i++) {
4836 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004837 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004838 AudioParameter inputCmd = AudioParameter();
4839 ALOGV("%s: inform input %d of device:%d", __func__,
4840 inputDescriptor->mIoHandle, device);
4841 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4842 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4843 inputCmd.toString(),
4844 delayMs);
4845 }
4846 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004847 }
Eric Laurente552edb2014-03-10 17:42:56 -07004848
4849 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004850 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004851
4852 return muteWaitMs;
4853}
4854
Eric Laurentc75307b2015-03-17 15:29:32 -07004855status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 int delayMs,
4857 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004858{
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 ssize_t index;
4860 if (patchHandle) {
4861 index = mAudioPatches.indexOfKey(*patchHandle);
4862 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004863 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 }
4865 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004866 return INVALID_OPERATION;
4867 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004868 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4869 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004870 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004871 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 removeAudioPatch(patchDesc->mHandle);
4873 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004874 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004875 return status;
4876}
4877
4878status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4879 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004880 bool force,
4881 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004882{
4883 status_t status = NO_ERROR;
4884
Eric Laurent1f2f2232014-06-02 12:01:23 -07004885 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4887 inputDesc->mDevice = device;
4888
4889 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4890 if (!deviceList.isEmpty()) {
4891 struct audio_patch patch;
4892 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004893 // AUDIO_SOURCE_HOTWORD is for internal use only:
4894 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004895 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004896 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004897 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4898 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004899 patch.num_sinks = 1;
4900 //only one input device for now
4901 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004902 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 ssize_t index;
4904 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4905 index = mAudioPatches.indexOfKey(*patchHandle);
4906 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004907 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 }
4909 sp< AudioPatch> patchDesc;
4910 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4911 if (index >= 0) {
4912 patchDesc = mAudioPatches.valueAt(index);
4913 afPatchHandle = patchDesc->mAfPatchHandle;
4914 }
4915
Eric Laurent1c333e22014-05-20 10:48:17 -07004916 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004918 0);
4919 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004920 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004921 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004923 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 addAudioPatch(patchDesc->mHandle, patchDesc);
4925 } else {
4926 patchDesc->mPatch = patch;
4927 }
4928 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004929 if (patchHandle) {
4930 *patchHandle = patchDesc->mHandle;
4931 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004932 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004934 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004935 }
4936 }
4937 }
4938 return status;
4939}
4940
Eric Laurent6a94d692014-05-20 11:18:06 -07004941status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4942 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004943{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004944 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 ssize_t index;
4946 if (patchHandle) {
4947 index = mAudioPatches.indexOfKey(*patchHandle);
4948 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004949 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 }
4951 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004952 return INVALID_OPERATION;
4953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4955 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004956 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004957 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 removeAudioPatch(patchDesc->mHandle);
4959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004961 return status;
4962}
4963
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004964sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004965 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01004966 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004967 audio_format_t& format,
4968 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004969 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004970{
4971 // Choose an input profile based on the requested capture parameters: select the first available
4972 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004973 //
4974 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4975 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004976
4977 for (size_t i = 0; i < mHwModules.size(); i++)
4978 {
4979 if (mHwModules[i]->mHandle == 0) {
4980 continue;
4981 }
4982 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4983 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004984 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004985 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004986 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004987 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004988 format,
4989 &format /*updatedFormat*/,
4990 channelMask,
4991 &channelMask /*updatedChannelMask*/,
4992 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004993
Eric Laurente552edb2014-03-10 17:42:56 -07004994 return profile;
4995 }
4996 }
4997 }
4998 return NULL;
4999}
5000
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005001
5002audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005003 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005004{
François Gaffie036e1e92015-03-19 10:16:24 +01005005 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5006 audio_devices_t selectedDeviceFromMix =
5007 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005008
François Gaffie036e1e92015-03-19 10:16:24 +01005009 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5010 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005011 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005012 return getDeviceForInputSource(inputSource);
5013}
5014
5015audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5016{
Paul McLean466dc8e2015-04-17 13:15:36 -06005017 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5018 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005019 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005020 return route->mDeviceDescriptor->type();
5021 }
5022 }
5023
5024 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005025}
5026
Eric Laurente0720872014-03-11 09:30:41 -07005027float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005028 int index,
5029 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005030{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005031 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005032
5033 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5034 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5035 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5036 // the ringtone volume
5037 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5038 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5039 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5040 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5041 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5042 }
5043
Eric Laurente552edb2014-03-10 17:42:56 -07005044 // if a headset is connected, apply the following rules to ring tones and notifications
5045 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005046 // - always attenuate notifications volume by 6dB
5047 // - attenuate ring tones volume by 6dB unless music is not playing and
5048 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005049 // - if music is playing, always limit the volume to current music volume,
5050 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005051 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005052 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5053 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5054 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5055 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5056 ((stream_strategy == STRATEGY_SONIFICATION)
5057 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005058 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005059 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005060 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005061 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005062 // when the phone is ringing we must consider that music could have been paused just before
5063 // by the music application and behave as if music was active if the last music track was
5064 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005065 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005066 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005067 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005068 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005069 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005070 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5071 musicDevice),
5072 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005073 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5074 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005075 if (volumeDB > minVolDB) {
5076 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005077 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005078 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005079 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5080 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5081 // on A2DP, also ensure notification volume is not too low compared to media when
5082 // intended to be played
5083 if ((volumeDB > -96.0f) &&
5084 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5085 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5086 stream, device,
5087 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5088 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5089 }
5090 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005091 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5092 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005093 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005094 }
5095 }
5096
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005097 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005098}
5099
Eric Laurente0720872014-03-11 09:30:41 -07005100status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005101 int index,
5102 const sp<AudioOutputDescriptor>& outputDesc,
5103 audio_devices_t device,
5104 int delayMs,
5105 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005106{
Eric Laurente552edb2014-03-10 17:42:56 -07005107 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005108 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005109 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005111 return NO_ERROR;
5112 }
François Gaffie2110e042015-03-24 08:41:51 +01005113 audio_policy_forced_cfg_t forceUseForComm =
5114 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005115 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005116 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5117 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005118 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005119 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005120 return INVALID_OPERATION;
5121 }
5122
Eric Laurentc75307b2015-03-17 15:29:32 -07005123 if (device == AUDIO_DEVICE_NONE) {
5124 device = outputDesc->device();
5125 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005126
Eric Laurentffbc80f2015-03-18 18:30:19 -07005127 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005128 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005129 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005130 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005131
Eric Laurentffbc80f2015-03-18 18:30:19 -07005132 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005133
Eric Laurent3b73df72014-03-11 09:06:29 -07005134 if (stream == AUDIO_STREAM_VOICE_CALL ||
5135 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005136 float voiceVolume;
5137 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005138 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005139 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005140 } else {
5141 voiceVolume = 1.0;
5142 }
5143
Eric Laurent18fba842016-03-31 14:41:26 -07005144 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005145 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5146 mLastVoiceVolume = voiceVolume;
5147 }
5148 }
5149
5150 return NO_ERROR;
5151}
5152
Eric Laurentc75307b2015-03-17 15:29:32 -07005153void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5154 audio_devices_t device,
5155 int delayMs,
5156 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005157{
Eric Laurentc75307b2015-03-17 15:29:32 -07005158 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005159
Eric Laurent794fde22016-03-11 09:50:45 -08005160 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005161 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005162 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005164 device,
5165 delayMs,
5166 force);
5167 }
5168}
5169
Eric Laurente0720872014-03-11 09:30:41 -07005170void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005171 bool on,
5172 const sp<AudioOutputDescriptor>& outputDesc,
5173 int delayMs,
5174 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005175{
Eric Laurent72249d52015-06-08 11:12:15 -07005176 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5177 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005178 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005179 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005181 }
5182 }
5183}
5184
Eric Laurente0720872014-03-11 09:30:41 -07005185void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005186 bool on,
5187 const sp<AudioOutputDescriptor>& outputDesc,
5188 int delayMs,
5189 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005190{
Eric Laurente552edb2014-03-10 17:42:56 -07005191 if (device == AUDIO_DEVICE_NONE) {
5192 device = outputDesc->device();
5193 }
5194
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5196 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005197
5198 if (on) {
5199 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005200 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005201 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005202 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005203 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005204 }
5205 }
5206 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5207 outputDesc->mMuteCount[stream]++;
5208 } else {
5209 if (outputDesc->mMuteCount[stream] == 0) {
5210 ALOGV("setStreamMute() unmuting non muted stream!");
5211 return;
5212 }
5213 if (--outputDesc->mMuteCount[stream] == 0) {
5214 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005215 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005216 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005217 device,
5218 delayMs);
5219 }
5220 }
5221}
5222
Eric Laurente0720872014-03-11 09:30:41 -07005223void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005224 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005225{
Eric Laurent87ffa392015-05-22 10:32:38 -07005226 if(!hasPrimaryOutput()) {
5227 return;
5228 }
5229
Eric Laurente552edb2014-03-10 17:42:56 -07005230 // if the stream pertains to sonification strategy and we are in call we must
5231 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5232 // in the device used for phone strategy and play the tone if the selected device does not
5233 // interfere with the device used for phone strategy
5234 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5235 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005236 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005237 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5238 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005240 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5241 stream, starting, outputDesc->mDevice, stateChange);
5242 if (outputDesc->mRefCount[stream]) {
5243 int muteCount = 1;
5244 if (stateChange) {
5245 muteCount = outputDesc->mRefCount[stream];
5246 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005247 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005248 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5249 for (int i = 0; i < muteCount; i++) {
5250 setStreamMute(stream, starting, mPrimaryOutput);
5251 }
5252 } else {
5253 ALOGV("handleIncallSonification() high visibility");
5254 if (outputDesc->device() &
5255 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5256 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5257 for (int i = 0; i < muteCount; i++) {
5258 setStreamMute(stream, starting, mPrimaryOutput);
5259 }
5260 }
5261 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005262 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5263 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005264 } else {
5265 mpClientInterface->stopTone();
5266 }
5267 }
5268 }
5269 }
5270}
5271
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005272audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5273{
5274 // flags to stream type mapping
5275 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5276 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5277 }
5278 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5279 return AUDIO_STREAM_BLUETOOTH_SCO;
5280 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005281 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5282 return AUDIO_STREAM_TTS;
5283 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005284
5285 // usage to stream type mapping
5286 switch (attr->usage) {
5287 case AUDIO_USAGE_MEDIA:
5288 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005289 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5290 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005291 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5292 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005293 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5294 return AUDIO_STREAM_SYSTEM;
5295 case AUDIO_USAGE_VOICE_COMMUNICATION:
5296 return AUDIO_STREAM_VOICE_CALL;
5297
5298 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5299 return AUDIO_STREAM_DTMF;
5300
5301 case AUDIO_USAGE_ALARM:
5302 return AUDIO_STREAM_ALARM;
5303 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5304 return AUDIO_STREAM_RING;
5305
5306 case AUDIO_USAGE_NOTIFICATION:
5307 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5308 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5309 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5310 case AUDIO_USAGE_NOTIFICATION_EVENT:
5311 return AUDIO_STREAM_NOTIFICATION;
5312
5313 case AUDIO_USAGE_UNKNOWN:
5314 default:
5315 return AUDIO_STREAM_MUSIC;
5316 }
5317}
Eric Laurente83b55d2014-11-14 10:06:21 -08005318
François Gaffie53615e22015-03-19 09:24:12 +01005319bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5320{
Eric Laurente83b55d2014-11-14 10:06:21 -08005321 // has flags that map to a strategy?
5322 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5323 return true;
5324 }
5325
5326 // has known usage?
5327 switch (paa->usage) {
5328 case AUDIO_USAGE_UNKNOWN:
5329 case AUDIO_USAGE_MEDIA:
5330 case AUDIO_USAGE_VOICE_COMMUNICATION:
5331 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5332 case AUDIO_USAGE_ALARM:
5333 case AUDIO_USAGE_NOTIFICATION:
5334 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5335 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5336 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5337 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5338 case AUDIO_USAGE_NOTIFICATION_EVENT:
5339 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5340 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5341 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5342 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005343 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005344 break;
5345 default:
5346 return false;
5347 }
5348 return true;
5349}
5350
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005351bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005352 routing_strategy strategy, uint32_t inPastMs,
5353 nsecs_t sysTime) const
5354{
5355 if ((sysTime == 0) && (inPastMs != 0)) {
5356 sysTime = systemTime();
5357 }
Eric Laurent794fde22016-03-11 09:50:45 -08005358 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005359 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5360 (NUM_STRATEGIES == strategy)) &&
5361 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5362 return true;
5363 }
5364 }
5365 return false;
5366}
5367
François Gaffie2110e042015-03-24 08:41:51 +01005368audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5369{
5370 return mEngine->getForceUse(usage);
5371}
5372
5373bool AudioPolicyManager::isInCall()
5374{
5375 return isStateInCall(mEngine->getPhoneState());
5376}
5377
5378bool AudioPolicyManager::isStateInCall(int state)
5379{
5380 return is_state_in_call(state);
5381}
5382
Eric Laurentd60560a2015-04-10 11:31:20 -07005383void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5384{
5385 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5386 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5387 if (sourceDesc->mDevice->equals(deviceDesc)) {
5388 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5389 stopAudioSource(sourceDesc->getHandle());
5390 }
5391 }
5392
5393 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5394 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5395 bool release = false;
5396 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5397 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5398 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5399 source->ext.device.type == deviceDesc->type()) {
5400 release = true;
5401 }
5402 }
5403 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5404 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5405 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5406 sink->ext.device.type == deviceDesc->type()) {
5407 release = true;
5408 }
5409 }
5410 if (release) {
5411 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5412 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5413 }
5414 }
5415}
5416
Phil Burk09bc4612016-02-24 15:58:15 -08005417// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005418void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5419 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005420 // TODO Set this based on Config properties.
5421 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005422
5423 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5424 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005425 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005426
5427 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005428 bool supportsAC3 = false;
5429 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005430 bool supportsIEC61937 = false;
5431 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5432 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005433 switch (format) {
5434 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005435 supportsAC3 = true;
5436 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005437 case AUDIO_FORMAT_E_AC3:
5438 case AUDIO_FORMAT_DTS:
5439 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005440 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005441 break;
5442 case AUDIO_FORMAT_IEC61937:
5443 supportsIEC61937 = true;
5444 break;
5445 default:
5446 break;
5447 }
5448 }
Phil Burk09bc4612016-02-24 15:58:15 -08005449
5450 // Modify formats based on surround preferences.
5451 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005452 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5453 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5454 // Remove surround sound related formats.
5455 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5456 audio_format_t format = formats[formatIndex];
5457 switch(format) {
5458 case AUDIO_FORMAT_AC3:
5459 case AUDIO_FORMAT_E_AC3:
5460 case AUDIO_FORMAT_DTS:
5461 case AUDIO_FORMAT_DTS_HD:
5462 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005463 formats.removeAt(formatIndex);
5464 break;
5465 default:
5466 formatIndex++; // keep it
5467 break;
5468 }
Phil Burk09bc4612016-02-24 15:58:15 -08005469 }
Phil Burk07ac1142016-03-25 13:39:29 -07005470 supportsAC3 = false;
5471 supportsOtherSurround = false;
5472 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005473 }
Phil Burk07ac1142016-03-25 13:39:29 -07005474 } else { // AUTO or ALWAYS
5475 // Most TVs support AC3 even if they do not report it in the EDID.
5476 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5477 && !supportsAC3) {
5478 formats.add(AUDIO_FORMAT_AC3);
5479 supportsAC3 = true;
5480 }
5481
5482 // If ALWAYS, add support for raw surround formats if all are missing.
5483 // This assumes that if any of these formats are reported by the HAL
5484 // then the report is valid and should not be modified.
5485 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5486 && !supportsOtherSurround) {
5487 formats.add(AUDIO_FORMAT_E_AC3);
5488 formats.add(AUDIO_FORMAT_DTS);
5489 formats.add(AUDIO_FORMAT_DTS_HD);
5490 supportsOtherSurround = true;
5491 }
5492
5493 // Add support for IEC61937 if any raw surround supported.
5494 // The HAL could do this but add it here, just in case.
5495 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5496 formats.add(AUDIO_FORMAT_IEC61937);
5497 supportsIEC61937 = true;
5498 }
Phil Burk09bc4612016-02-24 15:58:15 -08005499 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005500}
5501
5502// Modify the list of channel masks supported.
5503void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5504 ChannelsVector &channelMasks = *channelMasksPtr;
5505 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5506 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5507
5508 // If NEVER, then remove support for channelMasks > stereo.
5509 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5510 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5511 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5512 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5513 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5514 channelMasks.removeAt(maskIndex);
5515 } else {
5516 maskIndex++;
5517 }
5518 }
5519 // If ALWAYS, then make sure we at least support 5.1
5520 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5521 bool supports5dot1 = false;
5522 // Are there any channel masks that can be considered "surround"?
5523 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5524 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5525 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5526 supports5dot1 = true;
5527 break;
5528 }
5529 }
5530 // If not then add 5.1 support.
5531 if (!supports5dot1) {
5532 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5533 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5534 }
Phil Burk09bc4612016-02-24 15:58:15 -08005535 }
5536}
5537
Phil Burk00eeb322016-03-31 12:41:00 -07005538void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5539 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005540 AudioProfileVector &profiles)
5541{
5542 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005543
François Gaffie112b0af2015-11-19 16:13:25 +01005544 // Format MUST be checked first to update the list of AudioProfile
5545 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005546 reply = mpClientInterface->getParameters(
5547 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005548 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005549 AudioParameter repliedParameters(reply);
5550 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005551 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005552 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5553 return;
5554 }
Phil Burk09bc4612016-02-24 15:58:15 -08005555 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005556 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005557 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005558 }
Phil Burk09bc4612016-02-24 15:58:15 -08005559 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005560 }
5561 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5562
Eric Laurent20eb3a42016-01-26 18:39:17 -08005563 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005564 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005565 ChannelsVector channelMasks;
5566 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005567 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005568 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005569
5570 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005571 reply = mpClientInterface->getParameters(
5572 ioHandle,
5573 requestedParameters.toString() + ";" +
5574 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005575 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005576 AudioParameter repliedParameters(reply);
5577 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005578 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005579 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005580 }
5581 }
5582 if (profiles.hasDynamicChannelsFor(format)) {
5583 reply = mpClientInterface->getParameters(ioHandle,
5584 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005585 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005586 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005587 AudioParameter repliedParameters(reply);
5588 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005589 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005590 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005591 if (device == AUDIO_DEVICE_OUT_HDMI) {
5592 filterSurroundChannelMasks(&channelMasks);
5593 }
François Gaffie112b0af2015-11-19 16:13:25 +01005594 }
5595 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005596 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005597 }
5598}
Eric Laurentd60560a2015-04-10 11:31:20 -07005599
Eric Laurente552edb2014-03-10 17:42:56 -07005600}; // namespace android